Make QFtp private.
[profile/ivi/qtbase.git] / src / corelib / io / qprocess.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtCore module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 //#define QPROCESS_DEBUG
43
44 #if defined QPROCESS_DEBUG
45 #include <qdebug.h>
46 #include <qstring.h>
47 #include <ctype.h>
48 #if !defined(Q_OS_WINCE)
49 #include <errno.h>
50 #endif
51
52 QT_BEGIN_NAMESPACE
53 /*
54     Returns a human readable representation of the first \a len
55     characters in \a data.
56 */
57 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
58 {
59     if (!data) return "(null)";
60     QByteArray out;
61     for (int i = 0; i < len && i < maxSize; ++i) {
62         char c = data[i];
63         if (isprint(c)) {
64             out += c;
65         } else switch (c) {
66         case '\n': out += "\\n"; break;
67         case '\r': out += "\\r"; break;
68         case '\t': out += "\\t"; break;
69         default:
70             char buf[5];
71             qsnprintf(buf, sizeof(buf), "\\%3o", c);
72             buf[4] = '\0';
73             out += QByteArray(buf);
74         }
75     }
76
77     if (len < maxSize)
78         out += "...";
79
80     return out;
81 }
82
83 QT_END_NAMESPACE
84
85 #endif
86
87 #include "qprocess.h"
88 #include "qprocess_p.h"
89
90 #include <qbytearray.h>
91 #include <qelapsedtimer.h>
92 #include <qcoreapplication.h>
93 #include <qsocketnotifier.h>
94 #include <qtimer.h>
95
96 #ifdef Q_OS_WIN
97 #include <qwineventnotifier.h>
98 #endif
99
100 #ifdef Q_OS_SYMBIAN
101 #include <e32std.h>
102 #endif
103
104 #ifndef QT_NO_PROCESS
105
106 QT_BEGIN_NAMESPACE
107
108 /*!
109     \class QProcessEnvironment
110
111     \brief The QProcessEnvironment class holds the environment variables that
112     can be passed to a program.
113
114     \ingroup io
115     \ingroup misc
116     \mainclass
117     \reentrant
118     \since 4.6
119
120     A process's environment is composed of a set of key=value pairs known as
121     environment variables. The QProcessEnvironment class wraps that concept
122     and allows easy manipulation of those variables. It's meant to be used
123     along with QProcess, to set the environment for child processes. It
124     cannot be used to change the current process's environment.
125
126     The environment of the calling process can be obtained using
127     QProcessEnvironment::systemEnvironment().
128
129     On Unix systems, the variable names are case-sensitive. For that reason,
130     this class will not touch the names of the variables. Note as well that
131     Unix environment allows both variable names and contents to contain arbitrary
132     binary data (except for the NUL character), but this is not supported by
133     QProcessEnvironment. This class only supports names and values that are
134     encodable by the current locale settings (see QTextCodec::codecForLocale).
135
136     On Windows, the variable names are case-insensitive. Therefore,
137     QProcessEnvironment will always uppercase the names and do case-insensitive
138     comparisons.
139
140     On Windows CE, the concept of environment does not exist. This class will
141     keep the values set for compatibility with other platforms, but the values
142     set will have no effect on the processes being created.
143
144     \sa QProcess, QProcess::systemEnvironment(), QProcess::setProcessEnvironment()
145 */
146
147 QStringList QProcessEnvironmentPrivate::toList() const
148 {
149     QStringList result;
150     result.reserve(hash.size());
151     Hash::ConstIterator it = hash.constBegin(),
152                        end = hash.constEnd();
153     for ( ; it != end; ++it) {
154         QString data = nameToString(it.key());
155         QString value = valueToString(it.value());
156         data.reserve(data.length() + value.length() + 1);
157         data.append(QLatin1Char('='));
158         data.append(value);
159         result << data;
160     }
161     return result;
162 }
163
164 QProcessEnvironment QProcessEnvironmentPrivate::fromList(const QStringList &list)
165 {
166     QProcessEnvironment env;
167     QStringList::ConstIterator it = list.constBegin(),
168                               end = list.constEnd();
169     for ( ; it != end; ++it) {
170         int pos = it->indexOf(QLatin1Char('='));
171         if (pos < 1)
172             continue;
173
174         QString value = it->mid(pos + 1);
175         QString name = *it;
176         name.truncate(pos);
177         env.insert(name, value);
178     }
179     return env;
180 }
181
182 QStringList QProcessEnvironmentPrivate::keys() const
183 {
184     QStringList result;
185     result.reserve(hash.size());
186     Hash::ConstIterator it = hash.constBegin(),
187                        end = hash.constEnd();
188     for ( ; it != end; ++it)
189         result << nameToString(it.key());
190     return result;
191 }
192
193 void QProcessEnvironmentPrivate::insert(const QProcessEnvironmentPrivate &other)
194 {
195     Hash::ConstIterator it = other.hash.constBegin(),
196                        end = other.hash.constEnd();
197     for ( ; it != end; ++it)
198         hash.insert(it.key(), it.value());
199
200 #ifdef Q_OS_UNIX
201     QHash<QString, Key>::ConstIterator nit = other.nameMap.constBegin(),
202                                       nend = other.nameMap.constEnd();
203     for ( ; nit != nend; ++nit)
204         nameMap.insert(nit.key(), nit.value());
205 #endif
206 }
207
208 /*!
209     Creates a new QProcessEnvironment object. This constructor creates an
210     empty environment. If set on a QProcess, this will cause the current
211     environment variables to be removed.
212 */
213 QProcessEnvironment::QProcessEnvironment()
214     : d(0)
215 {
216 }
217
218 /*!
219     Frees the resources associated with this QProcessEnvironment object.
220 */
221 QProcessEnvironment::~QProcessEnvironment()
222 {
223 }
224
225 /*!
226     Creates a QProcessEnvironment object that is a copy of \a other.
227 */
228 QProcessEnvironment::QProcessEnvironment(const QProcessEnvironment &other)
229     : d(other.d)
230 {
231 }
232
233 /*!
234     Copies the contents of the \a other QProcessEnvironment object into this
235     one.
236 */
237 QProcessEnvironment &QProcessEnvironment::operator=(const QProcessEnvironment &other)
238 {
239     d = other.d;
240     return *this;
241 }
242
243 /*!
244     \fn bool QProcessEnvironment::operator !=(const QProcessEnvironment &other) const
245
246     Returns true if this and the \a other QProcessEnvironment objects are different.
247
248     \sa operator==()
249 */
250
251 /*!
252     Returns true if this and the \a other QProcessEnvironment objects are equal.
253
254     Two QProcessEnvironment objects are considered equal if they have the same
255     set of key=value pairs. The comparison of keys is done case-sensitive on
256     platforms where the environment is case-sensitive.
257
258     \sa operator!=(), contains()
259 */
260 bool QProcessEnvironment::operator==(const QProcessEnvironment &other) const
261 {
262     return d == other.d || (d && other.d && d->hash == other.d->hash);
263 }
264
265 /*!
266     Returns true if this QProcessEnvironment object is empty: that is
267     there are no key=value pairs set.
268
269     \sa clear(), systemEnvironment(), insert()
270 */
271 bool QProcessEnvironment::isEmpty() const
272 {
273     return d ? d->hash.isEmpty() : true;
274 }
275
276 /*!
277     Removes all key=value pairs from this QProcessEnvironment object, making
278     it empty.
279
280     \sa isEmpty(), systemEnvironment()
281 */
282 void QProcessEnvironment::clear()
283 {
284     if (d)
285         d->hash.clear();
286     // Unix: Don't clear d->nameMap, as the environment is likely to be
287     // re-populated with the same keys again.
288 }
289
290 /*!
291     Returns true if the environment variable of name \a name is found in
292     this QProcessEnvironment object.
293
294     On Windows, variable names are case-insensitive, so the key is converted
295     to uppercase before searching. On other systems, names are case-sensitive
296     so no trasformation is applied.
297
298     \sa insert(), value()
299 */
300 bool QProcessEnvironment::contains(const QString &name) const
301 {
302     return d ? d->hash.contains(d->prepareName(name)) : false;
303 }
304
305 /*!
306     Inserts the environment variable of name \a name and contents \a value
307     into this QProcessEnvironment object. If that variable already existed,
308     it is replaced by the new value.
309
310     On Windows, variable names are case-insensitive, so this function always
311     uppercases the variable name before inserting. On other systems, names
312     are case-sensitive, so no transformation is applied.
313
314     On most systems, inserting a variable with no contents will have the
315     same effect for applications as if the variable had not been set at all.
316     However, to guarantee that there are no incompatibilities, to remove a
317     variable, please use the remove() function.
318
319     \sa contains(), remove(), value()
320 */
321 void QProcessEnvironment::insert(const QString &name, const QString &value)
322 {
323     // d detaches from null
324     d->hash.insert(d->prepareName(name), d->prepareValue(value));
325 }
326
327 /*!
328     Removes the environment variable identified by \a name from this
329     QProcessEnvironment object. If that variable did not exist before,
330     nothing happens.
331
332     On Windows, variable names are case-insensitive, so the key is converted
333     to uppercase before searching. On other systems, names are case-sensitive
334     so no trasformation is applied.
335
336     \sa contains(), insert(), value()
337 */
338 void QProcessEnvironment::remove(const QString &name)
339 {
340     if (d)
341         d->hash.remove(d->prepareName(name));
342 }
343
344 /*!
345     Searches this QProcessEnvironment object for a variable identified by
346     \a name and returns its value. If the variable is not found in this object,
347     then \a defaultValue is returned instead.
348
349     On Windows, variable names are case-insensitive, so the key is converted
350     to uppercase before searching. On other systems, names are case-sensitive
351     so no trasformation is applied.
352
353     \sa contains(), insert(), remove()
354 */
355 QString QProcessEnvironment::value(const QString &name, const QString &defaultValue) const
356 {
357     if (!d)
358         return defaultValue;
359
360     QProcessEnvironmentPrivate::Hash::ConstIterator it = d->hash.constFind(d->prepareName(name));
361     if (it == d->hash.constEnd())
362         return defaultValue;
363
364     return d->valueToString(it.value());
365 }
366
367 /*!
368     Converts this QProcessEnvironment object into a list of strings, one for
369     each environment variable that is set. The environment variable's name
370     and its value are separated by an equal character ('=').
371
372     The QStringList contents returned by this function are suitable for use
373     with the QProcess::setEnvironment function. However, it is recommended
374     to use QProcess::setProcessEnvironment instead since that will avoid
375     unnecessary copying of the data.
376
377     \sa systemEnvironment(), QProcess::systemEnvironment(), QProcess::environment(),
378         QProcess::setEnvironment()
379 */
380 QStringList QProcessEnvironment::toStringList() const
381 {
382     return d ? d->toList() : QStringList();
383 }
384
385 /*!
386     \since 4.8
387
388     Returns a list containing all the variable names in this QProcessEnvironment
389     object.
390 */
391 QStringList QProcessEnvironment::keys() const
392 {
393     return d ? d->keys() : QStringList();
394 }
395
396 /*!
397     \overload
398     \since 4.8
399
400     Inserts the contents of \a e in this QProcessEnvironment object. Variables in
401     this object that also exist in \a e will be overwritten.
402 */
403 void QProcessEnvironment::insert(const QProcessEnvironment &e)
404 {
405     if (!e.d)
406         return;
407
408     // d detaches from null
409     d->insert(*e.d);
410 }
411
412 void QProcessPrivate::Channel::clear()
413 {
414     switch (type) {
415     case PipeSource:
416         Q_ASSERT(process);
417         process->stdinChannel.type = Normal;
418         process->stdinChannel.process = 0;
419         break;
420     case PipeSink:
421         Q_ASSERT(process);
422         process->stdoutChannel.type = Normal;
423         process->stdoutChannel.process = 0;
424         break;
425     }
426
427     type = Normal;
428     file.clear();
429     process = 0;
430 }
431
432 /*! \fn bool QProcessPrivate::startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid)
433
434 \internal
435  */
436
437 /*!
438     \class QProcess
439
440     \brief The QProcess class is used to start external programs and
441     to communicate with them.
442
443     \ingroup io
444
445     \reentrant
446
447     \section1 Running a Process
448
449     To start a process, pass the name and command line arguments of
450     the program you want to run as arguments to start(). Arguments
451     are supplied as individual strings in a QStringList.
452
453     For example, the following code snippet runs the analog clock
454     example in the Motif style on X11 platforms by passing strings
455     containing "-style" and "motif" as two items in the list of
456     arguments:
457
458     \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 0
459     \dots
460     \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 1
461     \snippet doc/src/snippets/qprocess/qprocess-simpleexecution.cpp 2
462
463     QProcess then enters the \l Starting state, and when the program
464     has started, QProcess enters the \l Running state and emits
465     started().
466
467     QProcess allows you to treat a process as a sequential I/O
468     device. You can write to and read from the process just as you
469     would access a network connection using QTcpSocket. You can then
470     write to the process's standard input by calling write(), and
471     read the standard output by calling read(), readLine(), and
472     getChar(). Because it inherits QIODevice, QProcess can also be
473     used as an input source for QXmlReader, or for generating data to
474     be uploaded using QNetworkAccessManager.
475
476     \note On Windows CE and Symbian, reading and writing to a process
477     is not supported.
478
479     When the process exits, QProcess reenters the \l NotRunning state
480     (the initial state), and emits finished().
481
482     The finished() signal provides the exit code and exit status of
483     the process as arguments, and you can also call exitCode() to
484     obtain the exit code of the last process that finished, and
485     exitStatus() to obtain its exit status. If an error occurs at
486     any point in time, QProcess will emit the error() signal. You
487     can also call error() to find the type of error that occurred
488     last, and state() to find the current process state.
489
490     \section1 Communicating via Channels
491
492     Processes have two predefined output channels: The standard
493     output channel (\c stdout) supplies regular console output, and
494     the standard error channel (\c stderr) usually supplies the
495     errors that are printed by the process. These channels represent
496     two separate streams of data. You can toggle between them by
497     calling setReadChannel(). QProcess emits readyRead() when data is
498     available on the current read channel. It also emits
499     readyReadStandardOutput() when new standard output data is
500     available, and when new standard error data is available,
501     readyReadStandardError() is emitted. Instead of calling read(),
502     readLine(), or getChar(), you can explicitly read all data from
503     either of the two channels by calling readAllStandardOutput() or
504     readAllStandardError().
505
506     The terminology for the channels can be misleading. Be aware that
507     the process's output channels correspond to QProcess's
508     \e read channels, whereas the process's input channels correspond
509     to QProcess's \e write channels. This is because what we read
510     using QProcess is the process's output, and what we write becomes
511     the process's input.
512
513     QProcess can merge the two output channels, so that standard
514     output and standard error data from the running process both use
515     the standard output channel. Call setProcessChannelMode() with
516     MergedChannels before starting the process to activative
517     this feature. You also have the option of forwarding the output of
518     the running process to the calling, main process, by passing
519     ForwardedChannels as the argument.
520
521     Certain processes need special environment settings in order to
522     operate. You can set environment variables for your process by
523     calling setEnvironment(). To set a working directory, call
524     setWorkingDirectory(). By default, processes are run in the
525     current working directory of the calling process.
526
527     \note On Symbian, setting environment or working directory
528     is not supported. The working directory will always be the private
529     directory of the running process.
530
531     \section1 Synchronous Process API
532
533     QProcess provides a set of functions which allow it to be used
534     without an event loop, by suspending the calling thread until
535     certain signals are emitted:
536
537     \list
538     \o waitForStarted() blocks until the process has started.
539
540     \o waitForReadyRead() blocks until new data is
541     available for reading on the current read channel.
542
543     \o waitForBytesWritten() blocks until one payload of
544     data has been written to the process.
545
546     \o waitForFinished() blocks until the process has finished.
547     \endlist
548
549     Calling these functions from the main thread (the thread that
550     calls QApplication::exec()) may cause your user interface to
551     freeze.
552
553     The following example runs \c gzip to compress the string "Qt
554     rocks!", without an event loop:
555
556     \snippet doc/src/snippets/process/process.cpp 0
557
558     \section1 Notes for Windows Users
559
560     Some Windows commands (for example, \c dir) are not provided by
561     separate applications, but by the command interpreter itself.
562     If you attempt to use QProcess to execute these commands directly,
563     it won't work. One possible solution is to execute the command
564     interpreter itself (\c{cmd.exe} on some Windows systems), and ask
565     the interpreter to execute the desired command.
566
567     \section1 Symbian Platform Security Requirements
568
569     On Symbian, processes which use the functions kill() or terminate()
570     must have the \c PowerMgmt platform security capability. If the client
571     process lacks this capability, these functions will fail.
572
573     Platform security capabilities are added via the
574     \l{qmake-variable-reference.html#target-capability}{TARGET.CAPABILITY}
575     qmake variable.
576
577     \sa QBuffer, QFile, QTcpSocket
578 */
579
580 /*!
581     \enum QProcess::ProcessChannel
582
583     This enum describes the process channels used by the running process.
584     Pass one of these values to setReadChannel() to set the
585     current read channel of QProcess.
586
587     \value StandardOutput The standard output (stdout) of the running
588            process.
589
590     \value StandardError The standard error (stderr) of the running
591            process.
592
593     \sa setReadChannel()
594 */
595
596 /*!
597     \enum QProcess::ProcessChannelMode
598
599     This enum describes the process channel modes of QProcess. Pass
600     one of these values to setProcessChannelMode() to set the
601     current read channel mode.
602
603     \value SeparateChannels QProcess manages the output of the
604     running process, keeping standard output and standard error data
605     in separate internal buffers. You can select the QProcess's
606     current read channel by calling setReadChannel(). This is the
607     default channel mode of QProcess.
608
609     \value MergedChannels QProcess merges the output of the running
610     process into the standard output channel (\c stdout). The
611     standard error channel (\c stderr) will not receive any data. The
612     standard output and standard error data of the running process
613     are interleaved.
614
615     \value ForwardedChannels QProcess forwards the output of the
616     running process onto the main process. Anything the child process
617     writes to its standard output and standard error will be written
618     to the standard output and standard error of the main process.
619
620     \note Windows intentionally suppresses output from GUI-only
621     applications to inherited consoles.
622     This does \e not apply to output redirected to files or pipes.
623     To forward the output of GUI-only applications on the console
624     nonetheless, you must use SeparateChannels and do the forwarding
625     yourself by reading the output and writing it to the appropriate
626     output channels.
627
628     \sa setProcessChannelMode()
629 */
630
631 /*!
632     \enum QProcess::ProcessError
633
634     This enum describes the different types of errors that are
635     reported by QProcess.
636
637     \value FailedToStart The process failed to start. Either the
638     invoked program is missing, or you may have insufficient
639     permissions to invoke the program.
640
641     \value Crashed The process crashed some time after starting
642     successfully.
643
644     \value Timedout The last waitFor...() function timed out. The
645     state of QProcess is unchanged, and you can try calling
646     waitFor...() again.
647
648     \value WriteError An error occurred when attempting to write to the
649     process. For example, the process may not be running, or it may
650     have closed its input channel.
651
652     \value ReadError An error occurred when attempting to read from
653     the process. For example, the process may not be running.
654
655     \value UnknownError An unknown error occurred. This is the default
656     return value of error().
657
658     \sa error()
659 */
660
661 /*!
662     \enum QProcess::ProcessState
663
664     This enum describes the different states of QProcess.
665
666     \value NotRunning The process is not running.
667
668     \value Starting The process is starting, but the program has not
669     yet been invoked.
670
671     \value Running The process is running and is ready for reading and
672     writing.
673
674     \sa state()
675 */
676
677 /*!
678     \enum QProcess::ExitStatus
679
680     This enum describes the different exit statuses of QProcess.
681
682     \value NormalExit The process exited normally.
683
684     \value CrashExit The process crashed.
685
686     \sa exitStatus()
687 */
688
689 /*!
690     \fn void QProcess::error(QProcess::ProcessError error)
691
692     This signal is emitted when an error occurs with the process. The
693     specified \a error describes the type of error that occurred.
694 */
695
696 /*!
697     \fn void QProcess::started()
698
699     This signal is emitted by QProcess when the process has started,
700     and state() returns \l Running.
701 */
702
703 /*!
704     \fn void QProcess::stateChanged(QProcess::ProcessState newState)
705
706     This signal is emitted whenever the state of QProcess changes. The
707     \a newState argument is the state QProcess changed to.
708 */
709
710 /*!
711     \fn void QProcess::finished(int exitCode)
712     \obsolete
713     \overload
714
715     Use finished(int exitCode, QProcess::ExitStatus status) instead.
716 */
717
718 /*!
719     \fn void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus)
720
721     This signal is emitted when the process finishes. \a exitCode is the exit
722     code of the process, and \a exitStatus is the exit status.  After the
723     process has finished, the buffers in QProcess are still intact. You can
724     still read any data that the process may have written before it finished.
725
726     \sa exitStatus()
727 */
728
729 /*!
730     \fn void QProcess::readyReadStandardOutput()
731
732     This signal is emitted when the process has made new data
733     available through its standard output channel (\c stdout). It is
734     emitted regardless of the current \l{readChannel()}{read channel}.
735
736     \sa readAllStandardOutput(), readChannel()
737 */
738
739 /*!
740     \fn void QProcess::readyReadStandardError()
741
742     This signal is emitted when the process has made new data
743     available through its standard error channel (\c stderr). It is
744     emitted regardless of the current \l{readChannel()}{read
745     channel}.
746
747     \sa readAllStandardError(), readChannel()
748 */
749
750 /*! \internal
751 */
752 QProcessPrivate::QProcessPrivate()
753 {
754     processChannel = QProcess::StandardOutput;
755     processChannelMode = QProcess::SeparateChannels;
756     processError = QProcess::UnknownError;
757     processState = QProcess::NotRunning;
758     pid = 0;
759     sequenceNumber = 0;
760     exitCode = 0;
761     exitStatus = QProcess::NormalExit;
762     startupSocketNotifier = 0;
763     deathNotifier = 0;
764     notifier = 0;
765     pipeWriter = 0;
766     childStartedPipe[0] = INVALID_Q_PIPE;
767     childStartedPipe[1] = INVALID_Q_PIPE;
768     deathPipe[0] = INVALID_Q_PIPE;
769     deathPipe[1] = INVALID_Q_PIPE;
770     exitCode = 0;
771     crashed = false;
772     dying = false;
773     emittedReadyRead = false;
774     emittedBytesWritten = false;
775 #ifdef Q_OS_WIN
776     pipeWriter = 0;
777     processFinishedNotifier = 0;
778 #endif // Q_OS_WIN
779 #ifdef Q_OS_UNIX
780     serial = 0;
781 #endif
782 #ifdef Q_OS_SYMBIAN
783     symbianProcess = NULL;
784     processLaunched = false;
785 #endif
786 }
787
788 /*! \internal
789 */
790 QProcessPrivate::~QProcessPrivate()
791 {
792     if (stdinChannel.process)
793         stdinChannel.process->stdoutChannel.clear();
794     if (stdoutChannel.process)
795         stdoutChannel.process->stdinChannel.clear();
796 }
797
798 /*! \internal
799 */
800 void QProcessPrivate::cleanup()
801 {
802     q_func()->setProcessState(QProcess::NotRunning);
803 #ifdef Q_OS_WIN
804     if (pid) {
805         CloseHandle(pid->hThread);
806         CloseHandle(pid->hProcess);
807         delete pid;
808         pid = 0;
809     }
810     if (processFinishedNotifier) {
811         processFinishedNotifier->setEnabled(false);
812         qDeleteInEventHandler(processFinishedNotifier);
813         processFinishedNotifier = 0;
814     }
815
816 #endif
817     pid = 0;
818     sequenceNumber = 0;
819     dying = false;
820
821     if (stdoutChannel.notifier) {
822         stdoutChannel.notifier->setEnabled(false);
823         qDeleteInEventHandler(stdoutChannel.notifier);
824         stdoutChannel.notifier = 0;
825     }
826     if (stderrChannel.notifier) {
827         stderrChannel.notifier->setEnabled(false);
828         qDeleteInEventHandler(stderrChannel.notifier);
829         stderrChannel.notifier = 0;
830     }
831     if (stdinChannel.notifier) {
832         stdinChannel.notifier->setEnabled(false);
833         qDeleteInEventHandler(stdinChannel.notifier);
834         stdinChannel.notifier = 0;
835     }
836     if (startupSocketNotifier) {
837         startupSocketNotifier->setEnabled(false);
838         qDeleteInEventHandler(startupSocketNotifier);
839         startupSocketNotifier = 0;
840     }
841     if (deathNotifier) {
842         deathNotifier->setEnabled(false);
843         qDeleteInEventHandler(deathNotifier);
844         deathNotifier = 0;
845     }
846     if (notifier) {
847         qDeleteInEventHandler(notifier);
848         notifier = 0;
849     }
850     destroyPipe(stdoutChannel.pipe);
851     destroyPipe(stderrChannel.pipe);
852     destroyPipe(stdinChannel.pipe);
853     destroyPipe(childStartedPipe);
854     destroyPipe(deathPipe);
855 #ifdef Q_OS_UNIX
856     serial = 0;
857 #endif
858 #ifdef Q_OS_SYMBIAN
859     if (symbianProcess) {
860         symbianProcess->Close();
861         delete symbianProcess;
862         symbianProcess = NULL;
863     }
864 #endif
865 }
866
867 /*! \internal
868 */
869 bool QProcessPrivate::_q_canReadStandardOutput()
870 {
871     Q_Q(QProcess);
872     qint64 available = bytesAvailableFromStdout();
873     if (available == 0) {
874         if (stdoutChannel.notifier)
875             stdoutChannel.notifier->setEnabled(false);
876         destroyPipe(stdoutChannel.pipe);
877 #if defined QPROCESS_DEBUG
878         qDebug("QProcessPrivate::canReadStandardOutput(), 0 bytes available");
879 #endif
880         return false;
881     }
882
883     char *ptr = outputReadBuffer.reserve(available);
884     qint64 readBytes = readFromStdout(ptr, available);
885     if (readBytes == -1) {
886         processError = QProcess::ReadError;
887         q->setErrorString(QProcess::tr("Error reading from process"));
888         emit q->error(processError);
889 #if defined QPROCESS_DEBUG
890         qDebug("QProcessPrivate::canReadStandardOutput(), failed to read from the process");
891 #endif
892         return false;
893     }
894 #if defined QPROCESS_DEBUG
895     qDebug("QProcessPrivate::canReadStandardOutput(), read %d bytes from the process' output",
896             int(readBytes));
897 #endif
898
899     if (stdoutChannel.closed) {
900         outputReadBuffer.chop(readBytes);
901         return false;
902     }
903
904     outputReadBuffer.chop(available - readBytes);
905
906     bool didRead = false;
907     if (readBytes == 0) {
908         if (stdoutChannel.notifier)
909             stdoutChannel.notifier->setEnabled(false);
910     } else if (processChannel == QProcess::StandardOutput) {
911         didRead = true;
912         if (!emittedReadyRead) {
913             emittedReadyRead = true;
914             emit q->readyRead();
915             emittedReadyRead = false;
916         }
917     }
918     emit q->readyReadStandardOutput();
919     return didRead;
920 }
921
922 /*! \internal
923 */
924 bool QProcessPrivate::_q_canReadStandardError()
925 {
926     Q_Q(QProcess);
927     qint64 available = bytesAvailableFromStderr();
928     if (available == 0) {
929         if (stderrChannel.notifier)
930             stderrChannel.notifier->setEnabled(false);
931         destroyPipe(stderrChannel.pipe);
932         return false;
933     }
934
935     char *ptr = errorReadBuffer.reserve(available);
936     qint64 readBytes = readFromStderr(ptr, available);
937     if (readBytes == -1) {
938         processError = QProcess::ReadError;
939         q->setErrorString(QProcess::tr("Error reading from process"));
940         emit q->error(processError);
941         return false;
942     }
943     if (stderrChannel.closed) {
944         errorReadBuffer.chop(readBytes);
945         return false;
946     }
947
948     errorReadBuffer.chop(available - readBytes);
949
950     bool didRead = false;
951     if (readBytes == 0) {
952         if (stderrChannel.notifier)
953             stderrChannel.notifier->setEnabled(false);
954     } else if (processChannel == QProcess::StandardError) {
955         didRead = true;
956         if (!emittedReadyRead) {
957             emittedReadyRead = true;
958             emit q->readyRead();
959             emittedReadyRead = false;
960         }
961     }
962     emit q->readyReadStandardError();
963     return didRead;
964 }
965
966 /*! \internal
967 */
968 bool QProcessPrivate::_q_canWrite()
969 {
970     Q_Q(QProcess);
971     if (stdinChannel.notifier)
972         stdinChannel.notifier->setEnabled(false);
973
974     if (writeBuffer.isEmpty()) {
975 #if defined QPROCESS_DEBUG
976         qDebug("QProcessPrivate::canWrite(), not writing anything (empty write buffer).");
977 #endif
978         return false;
979     }
980
981     qint64 written = writeToStdin(writeBuffer.readPointer(),
982                                       writeBuffer.nextDataBlockSize());
983     if (written < 0) {
984         destroyPipe(stdinChannel.pipe);
985         processError = QProcess::WriteError;
986         q->setErrorString(QProcess::tr("Error writing to process"));
987         emit q->error(processError);
988         return false;
989     }
990
991 #if defined QPROCESS_DEBUG
992     qDebug("QProcessPrivate::canWrite(), wrote %d bytes to the process input", int(written));
993 #endif
994
995     if (written != 0) {
996         writeBuffer.free(written);
997         if (!emittedBytesWritten) {
998             emittedBytesWritten = true;
999             emit q->bytesWritten(written);
1000             emittedBytesWritten = false;
1001         }
1002     }
1003     if (stdinChannel.notifier && !writeBuffer.isEmpty())
1004         stdinChannel.notifier->setEnabled(true);
1005     if (writeBuffer.isEmpty() && stdinChannel.closed)
1006         closeWriteChannel();
1007     return true;
1008 }
1009
1010 /*! \internal
1011 */
1012 bool QProcessPrivate::_q_processDied()
1013 {
1014     Q_Q(QProcess);
1015 #if defined QPROCESS_DEBUG
1016     qDebug("QProcessPrivate::_q_processDied()");
1017 #endif
1018 #ifdef Q_OS_UNIX
1019     if (!waitForDeadChild())
1020         return false;
1021 #endif
1022 #ifdef Q_OS_WIN
1023     if (processFinishedNotifier)
1024         processFinishedNotifier->setEnabled(false);
1025 #endif
1026
1027     // the process may have died before it got a chance to report that it was
1028     // either running or stopped, so we will call _q_startupNotification() and
1029     // give it a chance to emit started() or error(FailedToStart).
1030     if (processState == QProcess::Starting) {
1031         if (!_q_startupNotification())
1032             return true;
1033     }
1034
1035     if (dying) {
1036         // at this point we know the process is dead. prevent
1037         // reentering this slot recursively by calling waitForFinished()
1038         // or opening a dialog inside slots connected to the readyRead
1039         // signals emitted below.
1040         return true;
1041     }
1042     dying = true;
1043
1044     // in case there is data in the pipe line and this slot by chance
1045     // got called before the read notifications, call these two slots
1046     // so the data is made available before the process dies.
1047     _q_canReadStandardOutput();
1048     _q_canReadStandardError();
1049
1050     findExitCode();
1051
1052     if (crashed) {
1053         exitStatus = QProcess::CrashExit;
1054         processError = QProcess::Crashed;
1055         q->setErrorString(QProcess::tr("Process crashed"));
1056         emit q->error(processError);
1057     }
1058
1059     bool wasRunning = (processState == QProcess::Running);
1060
1061     cleanup();
1062
1063     if (wasRunning) {
1064         // we received EOF now:
1065         emit q->readChannelFinished();
1066         // in the future:
1067         //emit q->standardOutputClosed();
1068         //emit q->standardErrorClosed();
1069
1070         emit q->finished(exitCode);
1071         emit q->finished(exitCode, exitStatus);
1072     }
1073 #if defined QPROCESS_DEBUG
1074     qDebug("QProcessPrivate::_q_processDied() process is dead");
1075 #endif
1076     return true;
1077 }
1078
1079 /*! \internal
1080 */
1081 bool QProcessPrivate::_q_startupNotification()
1082 {
1083     Q_Q(QProcess);
1084 #if defined QPROCESS_DEBUG
1085     qDebug("QProcessPrivate::startupNotification()");
1086 #endif
1087
1088     if (startupSocketNotifier)
1089         startupSocketNotifier->setEnabled(false);
1090     if (processStarted()) {
1091         q->setProcessState(QProcess::Running);
1092         emit q->started();
1093         return true;
1094     }
1095
1096     q->setProcessState(QProcess::NotRunning);
1097     processError = QProcess::FailedToStart;
1098     emit q->error(processError);
1099 #ifdef Q_OS_UNIX
1100     // make sure the process manager removes this entry
1101     waitForDeadChild();
1102     findExitCode();
1103 #endif
1104     cleanup();
1105     return false;
1106 }
1107
1108 /*! \internal
1109 */
1110 void QProcessPrivate::closeWriteChannel()
1111 {
1112 #if defined QPROCESS_DEBUG
1113     qDebug("QProcessPrivate::closeWriteChannel()");
1114 #endif
1115     if (stdinChannel.notifier) {
1116         extern void qDeleteInEventHandler(QObject *o);
1117         stdinChannel.notifier->setEnabled(false);
1118         if (stdinChannel.notifier) {
1119             qDeleteInEventHandler(stdinChannel.notifier);
1120             stdinChannel.notifier = 0;
1121         }
1122     }
1123 #ifdef Q_OS_WIN
1124     // ### Find a better fix, feeding the process little by little
1125     // instead.
1126     flushPipeWriter();
1127 #endif
1128     destroyPipe(stdinChannel.pipe);
1129 }
1130
1131 /*!
1132     Constructs a QProcess object with the given \a parent.
1133 */
1134 QProcess::QProcess(QObject *parent)
1135     : QIODevice(*new QProcessPrivate, parent)
1136 {
1137 #if defined QPROCESS_DEBUG
1138     qDebug("QProcess::QProcess(%p)", parent);
1139 #endif
1140 }
1141
1142 /*!
1143     Destructs the QProcess object, i.e., killing the process.
1144
1145     Note that this function will not return until the process is
1146     terminated.
1147 */
1148 QProcess::~QProcess()
1149 {
1150     Q_D(QProcess);
1151     if (d->processState != NotRunning) {
1152         qWarning("QProcess: Destroyed while process is still running.");
1153         kill();
1154         waitForFinished();
1155     }
1156 #ifdef Q_OS_UNIX
1157     // make sure the process manager removes this entry
1158     d->findExitCode();
1159 #endif
1160     d->cleanup();
1161 }
1162
1163 /*!
1164     \obsolete
1165     Returns the read channel mode of the QProcess. This function is
1166     equivalent to processChannelMode()
1167
1168     \sa processChannelMode()
1169 */
1170 QProcess::ProcessChannelMode QProcess::readChannelMode() const
1171 {
1172     return processChannelMode();
1173 }
1174
1175 /*!
1176     \obsolete
1177
1178     Use setProcessChannelMode(\a mode) instead.
1179
1180     \sa setProcessChannelMode()
1181 */
1182 void QProcess::setReadChannelMode(ProcessChannelMode mode)
1183 {
1184     setProcessChannelMode(mode);
1185 }
1186
1187 /*!
1188     \since 4.2
1189
1190     Returns the channel mode of the QProcess standard output and
1191     standard error channels.
1192
1193     \sa setProcessChannelMode(), ProcessChannelMode, setReadChannel()
1194 */
1195 QProcess::ProcessChannelMode QProcess::processChannelMode() const
1196 {
1197     Q_D(const QProcess);
1198     return d->processChannelMode;
1199 }
1200
1201 /*!
1202     \since 4.2
1203
1204     Sets the channel mode of the QProcess standard output and standard
1205     error channels to the \a mode specified.
1206     This mode will be used the next time start() is called. For example:
1207
1208     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 0
1209
1210     \sa processChannelMode(), ProcessChannelMode, setReadChannel()
1211 */
1212 void QProcess::setProcessChannelMode(ProcessChannelMode mode)
1213 {
1214     Q_D(QProcess);
1215     d->processChannelMode = mode;
1216 }
1217
1218 /*!
1219     Returns the current read channel of the QProcess.
1220
1221     \sa setReadChannel()
1222 */
1223 QProcess::ProcessChannel QProcess::readChannel() const
1224 {
1225     Q_D(const QProcess);
1226     return d->processChannel;
1227 }
1228
1229 /*!
1230     Sets the current read channel of the QProcess to the given \a
1231     channel. The current input channel is used by the functions
1232     read(), readAll(), readLine(), and getChar(). It also determines
1233     which channel triggers QProcess to emit readyRead().
1234
1235     \sa readChannel()
1236 */
1237 void QProcess::setReadChannel(ProcessChannel channel)
1238 {
1239     Q_D(QProcess);
1240     if (d->processChannel != channel) {
1241         QByteArray buf = d->buffer.readAll();
1242         if (d->processChannel == QProcess::StandardOutput) {
1243             for (int i = buf.size() - 1; i >= 0; --i)
1244                 d->outputReadBuffer.ungetChar(buf.at(i));
1245         } else {
1246             for (int i = buf.size() - 1; i >= 0; --i)
1247                 d->errorReadBuffer.ungetChar(buf.at(i));
1248         }
1249     }
1250     d->processChannel = channel;
1251 }
1252
1253 /*!
1254     Closes the read channel \a channel. After calling this function,
1255     QProcess will no longer receive data on the channel. Any data that
1256     has already been received is still available for reading.
1257
1258     Call this function to save memory, if you are not interested in
1259     the output of the process.
1260
1261     \sa closeWriteChannel(), setReadChannel()
1262 */
1263 void QProcess::closeReadChannel(ProcessChannel channel)
1264 {
1265     Q_D(QProcess);
1266
1267     if (channel == StandardOutput)
1268         d->stdoutChannel.closed = true;
1269     else
1270         d->stderrChannel.closed = true;
1271 }
1272
1273 /*!
1274     Schedules the write channel of QProcess to be closed. The channel
1275     will close once all data has been written to the process. After
1276     calling this function, any attempts to write to the process will
1277     fail.
1278
1279     Closing the write channel is necessary for programs that read
1280     input data until the channel has been closed. For example, the
1281     program "more" is used to display text data in a console on both
1282     Unix and Windows. But it will not display the text data until
1283     QProcess's write channel has been closed. Example:
1284
1285     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 1
1286
1287     The write channel is implicitly opened when start() is called.
1288
1289     \sa closeReadChannel()
1290 */
1291 void QProcess::closeWriteChannel()
1292 {
1293     Q_D(QProcess);
1294     d->stdinChannel.closed = true; // closing
1295     if (d->writeBuffer.isEmpty())
1296         d->closeWriteChannel();
1297 }
1298
1299 /*!
1300     \since 4.2
1301
1302     Redirects the process' standard input to the file indicated by \a
1303     fileName. When an input redirection is in place, the QProcess
1304     object will be in read-only mode (calling write() will result in
1305     error).
1306
1307     If the file \a fileName does not exist at the moment start() is
1308     called or is not readable, starting the process will fail.
1309
1310     Calling setStandardInputFile() after the process has started has no
1311     effect.
1312
1313     \sa setStandardOutputFile(), setStandardErrorFile(),
1314         setStandardOutputProcess()
1315 */
1316 void QProcess::setStandardInputFile(const QString &fileName)
1317 {
1318     Q_D(QProcess);
1319     d->stdinChannel = fileName;
1320 }
1321
1322 /*!
1323     \since 4.2
1324
1325     Redirects the process' standard output to the file \a
1326     fileName. When the redirection is in place, the standard output
1327     read channel is closed: reading from it using read() will always
1328     fail, as will readAllStandardOutput().
1329
1330     If the file \a fileName doesn't exist at the moment start() is
1331     called, it will be created. If it cannot be created, the starting
1332     will fail.
1333
1334     If the file exists and \a mode is QIODevice::Truncate, the file
1335     will be truncated. Otherwise (if \a mode is QIODevice::Append),
1336     the file will be appended to.
1337
1338     Calling setStandardOutputFile() after the process has started has
1339     no effect.
1340
1341     \sa setStandardInputFile(), setStandardErrorFile(),
1342         setStandardOutputProcess()
1343 */
1344 void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode)
1345 {
1346     Q_ASSERT(mode == Append || mode == Truncate);
1347     Q_D(QProcess);
1348
1349     d->stdoutChannel = fileName;
1350     d->stdoutChannel.append = mode == Append;
1351 }
1352
1353 /*!
1354     \since 4.2
1355
1356     Redirects the process' standard error to the file \a
1357     fileName. When the redirection is in place, the standard error
1358     read channel is closed: reading from it using read() will always
1359     fail, as will readAllStandardError(). The file will be appended to
1360     if \a mode is Append, otherwise, it will be truncated.
1361
1362     See setStandardOutputFile() for more information on how the file
1363     is opened.
1364
1365     Note: if setProcessChannelMode() was called with an argument of
1366     QProcess::MergedChannels, this function has no effect.
1367
1368     \sa setStandardInputFile(), setStandardOutputFile(),
1369         setStandardOutputProcess()
1370 */
1371 void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode)
1372 {
1373     Q_ASSERT(mode == Append || mode == Truncate);
1374     Q_D(QProcess);
1375
1376     d->stderrChannel = fileName;
1377     d->stderrChannel.append = mode == Append;
1378 }
1379
1380 /*!
1381     \since 4.2
1382
1383     Pipes the standard output stream of this process to the \a
1384     destination process' standard input.
1385
1386     The following shell command:
1387     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 2
1388
1389     Can be accomplished with QProcesses with the following code:
1390     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 3
1391 */
1392 void QProcess::setStandardOutputProcess(QProcess *destination)
1393 {
1394     QProcessPrivate *dfrom = d_func();
1395     QProcessPrivate *dto = destination->d_func();
1396     dfrom->stdoutChannel.pipeTo(dto);
1397     dto->stdinChannel.pipeFrom(dfrom);
1398 }
1399
1400 #if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
1401
1402 /*!
1403     \since 4.7
1404
1405     Returns the additional native command line arguments for the program.
1406
1407     \note This function is available only on the Windows and Symbian
1408     platforms.
1409
1410     \sa setNativeArguments()
1411 */
1412 QString QProcess::nativeArguments() const
1413 {
1414     Q_D(const QProcess);
1415     return d->nativeArguments;
1416 }
1417
1418 /*!
1419     \since 4.7
1420     \overload
1421
1422     Sets additional native command line \a arguments for the program.
1423
1424     On operating systems where the system API for passing command line
1425     \a arguments to a subprocess natively uses a single string, one can
1426     conceive command lines which cannot be passed via QProcess's portable
1427     list-based API. In such cases this function must be used to set a
1428     string which is \e appended to the string composed from the usual
1429     argument list, with a delimiting space.
1430
1431     \note This function is available only on the Windows and Symbian
1432     platforms.
1433
1434     \sa nativeArguments()
1435 */
1436 void QProcess::setNativeArguments(const QString &arguments)
1437 {
1438     Q_D(QProcess);
1439     d->nativeArguments = arguments;
1440 }
1441
1442 #endif
1443
1444 /*!
1445     If QProcess has been assigned a working directory, this function returns
1446     the working directory that the QProcess will enter before the program has
1447     started. Otherwise, (i.e., no directory has been assigned,) an empty
1448     string is returned, and QProcess will use the application's current
1449     working directory instead.
1450
1451     \sa setWorkingDirectory()
1452 */
1453 QString QProcess::workingDirectory() const
1454 {
1455     Q_D(const QProcess);
1456     return d->workingDirectory;
1457 }
1458
1459 /*!
1460     Sets the working directory to \a dir. QProcess will start the
1461     process in this directory. The default behavior is to start the
1462     process in the working directory of the calling process.
1463
1464     \note The working directory setting is ignored on Symbian;
1465     the private directory of the process is considered its working
1466     directory.
1467
1468     \sa workingDirectory(), start()
1469 */
1470 void QProcess::setWorkingDirectory(const QString &dir)
1471 {
1472     Q_D(QProcess);
1473     d->workingDirectory = dir;
1474 }
1475
1476 /*!
1477     Returns the native process identifier for the running process, if
1478     available.  If no process is currently running, 0 is returned.
1479 */
1480 Q_PID QProcess::pid() const
1481 {
1482     Q_D(const QProcess);
1483     return d->pid;
1484 }
1485
1486 /*! \reimp
1487
1488     This function operates on the current read channel.
1489
1490     \sa readChannel(), setReadChannel()
1491 */
1492 bool QProcess::canReadLine() const
1493 {
1494     Q_D(const QProcess);
1495     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1496                                     ? &d->errorReadBuffer
1497                                     : &d->outputReadBuffer;
1498     return readBuffer->canReadLine() || QIODevice::canReadLine();
1499 }
1500
1501 /*!
1502     Closes all communication with the process and kills it. After calling this
1503     function, QProcess will no longer emit readyRead(), and data can no
1504     longer be read or written.
1505 */
1506 void QProcess::close()
1507 {
1508     emit aboutToClose();
1509     while (waitForBytesWritten(-1))
1510         ;
1511     kill();
1512     waitForFinished(-1);
1513     QIODevice::close();
1514 }
1515
1516 /*! \reimp
1517
1518    Returns true if the process is not running, and no more data is available
1519    for reading; otherwise returns false.
1520 */
1521 bool QProcess::atEnd() const
1522 {
1523     Q_D(const QProcess);
1524     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1525                                     ? &d->errorReadBuffer
1526                                     : &d->outputReadBuffer;
1527     return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
1528 }
1529
1530 /*! \reimp
1531 */
1532 bool QProcess::isSequential() const
1533 {
1534     return true;
1535 }
1536
1537 /*! \reimp
1538 */
1539 qint64 QProcess::bytesAvailable() const
1540 {
1541     Q_D(const QProcess);
1542     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1543                                     ? &d->errorReadBuffer
1544                                     : &d->outputReadBuffer;
1545 #if defined QPROCESS_DEBUG
1546     qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
1547            (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
1548 #endif
1549     return readBuffer->size() + QIODevice::bytesAvailable();
1550 }
1551
1552 /*! \reimp
1553 */
1554 qint64 QProcess::bytesToWrite() const
1555 {
1556     Q_D(const QProcess);
1557     qint64 size = d->writeBuffer.size();
1558 #ifdef Q_OS_WIN
1559     size += d->pipeWriterBytesToWrite();
1560 #endif
1561     return size;
1562 }
1563
1564 /*!
1565     Returns the type of error that occurred last.
1566
1567     \sa state()
1568 */
1569 QProcess::ProcessError QProcess::error() const
1570 {
1571     Q_D(const QProcess);
1572     return d->processError;
1573 }
1574
1575 /*!
1576     Returns the current state of the process.
1577
1578     \sa stateChanged(), error()
1579 */
1580 QProcess::ProcessState QProcess::state() const
1581 {
1582     Q_D(const QProcess);
1583     return d->processState;
1584 }
1585
1586 /*!
1587     \deprecated
1588     Sets the environment that QProcess will use when starting a process to the
1589     \a environment specified which consists of a list of key=value pairs.
1590
1591     For example, the following code adds the \c{C:\\BIN} directory to the list of
1592     executable paths (\c{PATHS}) on Windows:
1593
1594     \snippet doc/src/snippets/qprocess-environment/main.cpp 0
1595
1596     \note This function is less efficient than the setProcessEnvironment()
1597     function.
1598
1599     \sa environment(), setProcessEnvironment(), systemEnvironment()
1600 */
1601 void QProcess::setEnvironment(const QStringList &environment)
1602 {
1603     setProcessEnvironment(QProcessEnvironmentPrivate::fromList(environment));
1604 }
1605
1606 /*!
1607     \deprecated
1608     Returns the environment that QProcess will use when starting a
1609     process, or an empty QStringList if no environment has been set
1610     using setEnvironment() or setEnvironmentHash(). If no environment
1611     has been set, the environment of the calling process will be used.
1612
1613     \note The environment settings are ignored on Windows CE and Symbian,
1614     as there is no concept of an environment.
1615
1616     \sa processEnvironment(), setEnvironment(), systemEnvironment()
1617 */
1618 QStringList QProcess::environment() const
1619 {
1620     Q_D(const QProcess);
1621     return d->environment.toStringList();
1622 }
1623
1624 /*!
1625     \since 4.6
1626     Sets the environment that QProcess will use when starting a process to the
1627     \a environment object.
1628
1629     For example, the following code adds the \c{C:\\BIN} directory to the list of
1630     executable paths (\c{PATHS}) on Windows and sets \c{TMPDIR}:
1631
1632     \snippet doc/src/snippets/qprocess-environment/main.cpp 1
1633
1634     Note how, on Windows, environment variable names are case-insensitive.
1635
1636     \sa processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
1637 */
1638 void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)
1639 {
1640     Q_D(QProcess);
1641     d->environment = environment;
1642 }
1643
1644 /*!
1645     \since 4.6
1646     Returns the environment that QProcess will use when starting a
1647     process, or an empty object if no environment has been set using
1648     setEnvironment() or setProcessEnvironment(). If no environment has
1649     been set, the environment of the calling process will be used.
1650
1651     \note The environment settings are ignored on Windows CE,
1652     as there is no concept of an environment.
1653
1654     \sa setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
1655 */
1656 QProcessEnvironment QProcess::processEnvironment() const
1657 {
1658     Q_D(const QProcess);
1659     return d->environment;
1660 }
1661
1662 /*!
1663     Blocks until the process has started and the started() signal has
1664     been emitted, or until \a msecs milliseconds have passed.
1665
1666     Returns true if the process was started successfully; otherwise
1667     returns false (if the operation timed out or if an error
1668     occurred).
1669
1670     This function can operate without an event loop. It is
1671     useful when writing non-GUI applications and when performing
1672     I/O operations in a non-GUI thread.
1673
1674     \warning Calling this function from the main (GUI) thread
1675     might cause your user interface to freeze.
1676
1677     If msecs is -1, this function will not time out.
1678
1679     \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
1680 */
1681 bool QProcess::waitForStarted(int msecs)
1682 {
1683     Q_D(QProcess);
1684     if (d->processState == QProcess::Running)
1685         return true;
1686
1687     return d->waitForStarted(msecs);
1688 }
1689
1690 /*! \reimp
1691 */
1692 bool QProcess::waitForReadyRead(int msecs)
1693 {
1694     Q_D(QProcess);
1695
1696     if (d->processState == QProcess::NotRunning)
1697         return false;
1698     if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1699         return false;
1700     if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
1701         return false;
1702     return d->waitForReadyRead(msecs);
1703 }
1704
1705 /*! \reimp
1706 */
1707 bool QProcess::waitForBytesWritten(int msecs)
1708 {
1709     Q_D(QProcess);
1710     if (d->processState == QProcess::NotRunning)
1711         return false;
1712     if (d->processState == QProcess::Starting) {
1713         QElapsedTimer stopWatch;
1714         stopWatch.start();
1715         bool started = waitForStarted(msecs);
1716         if (!started)
1717             return false;
1718         if (msecs != -1)
1719             msecs -= stopWatch.elapsed();
1720     }
1721
1722     return d->waitForBytesWritten(msecs);
1723 }
1724
1725 /*!
1726     Blocks until the process has finished and the finished() signal
1727     has been emitted, or until \a msecs milliseconds have passed.
1728
1729     Returns true if the process finished; otherwise returns false (if
1730     the operation timed out, if an error occurred, or if this QProcess
1731     is already finished).
1732
1733     This function can operate without an event loop. It is
1734     useful when writing non-GUI applications and when performing
1735     I/O operations in a non-GUI thread.
1736
1737     \warning Calling this function from the main (GUI) thread
1738     might cause your user interface to freeze.
1739
1740     If msecs is -1, this function will not time out.
1741
1742     \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
1743 */
1744 bool QProcess::waitForFinished(int msecs)
1745 {
1746     Q_D(QProcess);
1747     if (d->processState == QProcess::NotRunning)
1748         return false;
1749     if (d->processState == QProcess::Starting) {
1750         QElapsedTimer stopWatch;
1751         stopWatch.start();
1752         bool started = waitForStarted(msecs);
1753         if (!started)
1754             return false;
1755         if (msecs != -1)
1756             msecs -= stopWatch.elapsed();
1757     }
1758
1759     return d->waitForFinished(msecs);
1760 }
1761
1762 /*!
1763     Sets the current state of the QProcess to the \a state specified.
1764
1765     \sa state()
1766 */
1767 void QProcess::setProcessState(ProcessState state)
1768 {
1769     Q_D(QProcess);
1770     if (d->processState == state)
1771         return;
1772     d->processState = state;
1773     emit stateChanged(state);
1774 }
1775
1776 /*!
1777   This function is called in the child process context just before the
1778     program is executed on Unix or Mac OS X (i.e., after \e fork(), but before
1779     \e execve()). Reimplement this function to do last minute initialization
1780     of the child process. Example:
1781
1782     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 4
1783
1784     You cannot exit the process (by calling exit(), for instance) from
1785     this function. If you need to stop the program before it starts
1786     execution, your workaround is to emit finished() and then call
1787     exit().
1788
1789     \warning This function is called by QProcess on Unix and Mac OS X
1790     only. On Windows, it is not called.
1791 */
1792 void QProcess::setupChildProcess()
1793 {
1794 }
1795
1796 /*! \reimp
1797 */
1798 qint64 QProcess::readData(char *data, qint64 maxlen)
1799 {
1800     Q_D(QProcess);
1801     QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1802                               ? &d->errorReadBuffer
1803                               : &d->outputReadBuffer;
1804
1805     if (maxlen == 1 && !readBuffer->isEmpty()) {
1806         int c = readBuffer->getChar();
1807         if (c == -1) {
1808 #if defined QPROCESS_DEBUG
1809             qDebug("QProcess::readData(%p \"%s\", %d) == -1",
1810                    data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1811 #endif
1812             return -1;
1813         }
1814         *data = (char) c;
1815 #if defined QPROCESS_DEBUG
1816         qDebug("QProcess::readData(%p \"%s\", %d) == 1",
1817                data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1818 #endif
1819         return 1;
1820     }
1821
1822     qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
1823     qint64 readSoFar = 0;
1824     while (readSoFar < bytesToRead) {
1825         const char *ptr = readBuffer->readPointer();
1826         int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
1827                                             readBuffer->nextDataBlockSize());
1828         memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
1829         readSoFar += bytesToReadFromThisBlock;
1830         readBuffer->free(bytesToReadFromThisBlock);
1831     }
1832
1833 #if defined QPROCESS_DEBUG
1834     qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
1835            data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
1836 #endif
1837     if (!readSoFar && d->processState == QProcess::NotRunning)
1838         return -1;              // EOF
1839     return readSoFar;
1840 }
1841
1842 /*! \reimp
1843 */
1844 qint64 QProcess::writeData(const char *data, qint64 len)
1845 {
1846     Q_D(QProcess);
1847
1848 #if defined(Q_OS_WINCE)
1849     Q_UNUSED(data);
1850     Q_UNUSED(len);
1851     d->processError = QProcess::WriteError;
1852     setErrorString(tr("Error writing to process"));
1853     emit error(d->processError);
1854     return -1;
1855 #endif
1856
1857     if (d->stdinChannel.closed) {
1858 #if defined QPROCESS_DEBUG
1859     qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1860            data, qt_prettyDebug(data, len, 16).constData(), len);
1861 #endif
1862         return 0;
1863     }
1864
1865     if (len == 1) {
1866         d->writeBuffer.putChar(*data);
1867         if (d->stdinChannel.notifier)
1868             d->stdinChannel.notifier->setEnabled(true);
1869 #if defined QPROCESS_DEBUG
1870     qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
1871            data, qt_prettyDebug(data, len, 16).constData(), len);
1872 #endif
1873         return 1;
1874     }
1875
1876     char *dest = d->writeBuffer.reserve(len);
1877     memcpy(dest, data, len);
1878     if (d->stdinChannel.notifier)
1879         d->stdinChannel.notifier->setEnabled(true);
1880 #if defined QPROCESS_DEBUG
1881     qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
1882            data, qt_prettyDebug(data, len, 16).constData(), len, len);
1883 #endif
1884     return len;
1885 }
1886
1887 /*!
1888     Regardless of the current read channel, this function returns all
1889     data available from the standard output of the process as a
1890     QByteArray.
1891
1892     \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
1893 */
1894 QByteArray QProcess::readAllStandardOutput()
1895 {
1896     ProcessChannel tmp = readChannel();
1897     setReadChannel(StandardOutput);
1898     QByteArray data = readAll();
1899     setReadChannel(tmp);
1900     return data;
1901 }
1902
1903 /*!
1904     Regardless of the current read channel, this function returns all
1905     data available from the standard error of the process as a
1906     QByteArray.
1907
1908     \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
1909 */
1910 QByteArray QProcess::readAllStandardError()
1911 {
1912     ProcessChannel tmp = readChannel();
1913     setReadChannel(StandardError);
1914     QByteArray data = readAll();
1915     setReadChannel(tmp);
1916     return data;
1917 }
1918
1919 /*!
1920     Starts the given \a program in a new process, if none is already
1921     running, passing the command line arguments in \a arguments. The OpenMode
1922     is set to \a mode.
1923
1924     The QProcess object will immediately enter the Starting state. If the
1925     process starts successfully, QProcess will emit started(); otherwise,
1926     error() will be emitted. If the QProcess object is already running a
1927     process, a warning may be printed at the console, and the existing
1928     process will continue running.
1929
1930     \note Processes are started asynchronously, which means the started()
1931     and error() signals may be delayed. Call waitForStarted() to make
1932     sure the process has started (or has failed to start) and those signals
1933     have been emitted.
1934
1935     \note No further splitting of the arguments is performed.
1936
1937     \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
1938
1939     \sa pid(), started(), waitForStarted()
1940 */
1941 void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
1942 {
1943     Q_D(QProcess);
1944     if (d->processState != NotRunning) {
1945         qWarning("QProcess::start: Process is already running");
1946         return;
1947     }
1948
1949 #if defined QPROCESS_DEBUG
1950     qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
1951 #endif
1952
1953     d->outputReadBuffer.clear();
1954     d->errorReadBuffer.clear();
1955
1956     if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
1957         mode &= ~WriteOnly;     // not open for writing
1958     if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
1959         (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
1960          d->processChannelMode == MergedChannels))
1961         mode &= ~ReadOnly;      // not open for reading
1962     if (mode == 0)
1963         mode = Unbuffered;
1964     QIODevice::open(mode);
1965
1966     d->stdinChannel.closed = false;
1967     d->stdoutChannel.closed = false;
1968     d->stderrChannel.closed = false;
1969
1970     d->program = program;
1971     d->arguments = arguments;
1972
1973     d->exitCode = 0;
1974     d->exitStatus = NormalExit;
1975     d->processError = QProcess::UnknownError;
1976     d->errorString.clear();
1977     d->startProcess();
1978 }
1979
1980
1981 static QStringList parseCombinedArgString(const QString &program)
1982 {
1983     QStringList args;
1984     QString tmp;
1985     int quoteCount = 0;
1986     bool inQuote = false;
1987
1988     // handle quoting. tokens can be surrounded by double quotes
1989     // "hello world". three consecutive double quotes represent
1990     // the quote character itself.
1991     for (int i = 0; i < program.size(); ++i) {
1992         if (program.at(i) == QLatin1Char('"')) {
1993             ++quoteCount;
1994             if (quoteCount == 3) {
1995                 // third consecutive quote
1996                 quoteCount = 0;
1997                 tmp += program.at(i);
1998             }
1999             continue;
2000         }
2001         if (quoteCount) {
2002             if (quoteCount == 1)
2003                 inQuote = !inQuote;
2004             quoteCount = 0;
2005         }
2006         if (!inQuote && program.at(i).isSpace()) {
2007             if (!tmp.isEmpty()) {
2008                 args += tmp;
2009                 tmp.clear();
2010             }
2011         } else {
2012             tmp += program.at(i);
2013         }
2014     }
2015     if (!tmp.isEmpty())
2016         args += tmp;
2017
2018     return args;
2019 }
2020
2021 /*!
2022     \overload
2023
2024     Starts the program \a program in a new process, if one is not already
2025     running. \a program is a single string of text containing both the
2026     program name and its arguments. The arguments are separated by one or
2027     more spaces. For example:
2028
2029     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 5
2030
2031     The \a program string can also contain quotes, to ensure that arguments
2032     containing spaces are correctly supplied to the new process. For example:
2033
2034     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 6
2035
2036     If the QProcess object is already running a process, a warning may be
2037     printed at the console, and the existing process will continue running.
2038
2039     Note that, on Windows, quotes need to be both escaped and quoted.
2040     For example, the above code would be specified in the following
2041     way to ensure that \c{"My Documents"} is used as the argument to
2042     the \c dir executable:
2043
2044     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 7
2045
2046     The OpenMode is set to \a mode.
2047 */
2048 void QProcess::start(const QString &program, OpenMode mode)
2049 {
2050     QStringList args = parseCombinedArgString(program);
2051     if (args.isEmpty()) {
2052         Q_D(QProcess);
2053         d->processError = QProcess::FailedToStart;
2054         setErrorString(tr("No program defined"));
2055         emit error(d->processError);
2056         return;
2057     }
2058
2059     QString prog = args.first();
2060     args.removeFirst();
2061
2062     start(prog, args, mode);
2063 }
2064
2065 /*!
2066     Attempts to terminate the process.
2067
2068     The process may not exit as a result of calling this function (it is given
2069     the chance to prompt the user for any unsaved files, etc).
2070
2071     On Windows, terminate() posts a WM_CLOSE message to all toplevel windows
2072     of the process and then to the main thread of the process itself. On Unix
2073     and Mac OS X the SIGTERM signal is sent.
2074
2075     Console applications on Windows that do not run an event loop, or whose
2076     event loop does not handle the WM_CLOSE message, can only be terminated by
2077     calling kill().
2078
2079     On Symbian, this function requires platform security capability
2080     \c PowerMgmt. If absent, the process will panic with KERN-EXEC 46.
2081
2082     \note Terminating running processes from other processes will typically
2083     cause a panic in Symbian due to platform security.
2084
2085     \sa {Symbian Platform Security Requirements}
2086     \sa kill()
2087 */
2088 void QProcess::terminate()
2089 {
2090     Q_D(QProcess);
2091     d->terminateProcess();
2092 }
2093
2094 /*!
2095     Kills the current process, causing it to exit immediately.
2096
2097     On Windows, kill() uses TerminateProcess, and on Unix and Mac OS X, the
2098     SIGKILL signal is sent to the process.
2099
2100     On Symbian, this function requires platform security capability
2101     \c PowerMgmt. If absent, the process will panic with KERN-EXEC 46.
2102
2103     \note Killing running processes from other processes will typically
2104     cause a panic in Symbian due to platform security.
2105
2106     \sa {Symbian Platform Security Requirements}
2107     \sa terminate()
2108 */
2109 void QProcess::kill()
2110 {
2111     Q_D(QProcess);
2112     d->killProcess();
2113 }
2114
2115 /*!
2116     Returns the exit code of the last process that finished.
2117 */
2118 int QProcess::exitCode() const
2119 {
2120     Q_D(const QProcess);
2121     return d->exitCode;
2122 }
2123
2124 /*!
2125     \since 4.1
2126
2127     Returns the exit status of the last process that finished.
2128
2129     On Windows, if the process was terminated with TerminateProcess()
2130     from another application this function will still return NormalExit
2131     unless the exit code is less than 0.
2132 */
2133 QProcess::ExitStatus QProcess::exitStatus() const
2134 {
2135     Q_D(const QProcess);
2136     return d->exitStatus;
2137 }
2138
2139 /*!
2140     Starts the program \a program with the arguments \a arguments in a
2141     new process, waits for it to finish, and then returns the exit
2142     code of the process. Any data the new process writes to the
2143     console is forwarded to the calling process.
2144
2145     The environment and working directory are inherited from the calling
2146     process.
2147
2148     On Windows, arguments that contain spaces are wrapped in quotes.
2149
2150     If the process cannot be started, -2 is returned. If the process
2151     crashes, -1 is returned. Otherwise, the process' exit code is
2152     returned.
2153 */
2154 int QProcess::execute(const QString &program, const QStringList &arguments)
2155 {
2156     QProcess process;
2157     process.setReadChannelMode(ForwardedChannels);
2158     process.start(program, arguments);
2159     if (!process.waitForFinished(-1))
2160         return -2;
2161     return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2162 }
2163
2164 /*!
2165     \overload
2166
2167     Starts the program \a program in a new process. \a program is a
2168     single string of text containing both the program name and its
2169     arguments. The arguments are separated by one or more spaces.
2170 */
2171 int QProcess::execute(const QString &program)
2172 {
2173     QProcess process;
2174     process.setReadChannelMode(ForwardedChannels);
2175     process.start(program);
2176     if (!process.waitForFinished(-1))
2177         return -2;
2178     return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2179 }
2180
2181 /*!
2182     Starts the program \a program with the arguments \a arguments in a
2183     new process, and detaches from it. Returns true on success;
2184     otherwise returns false. If the calling process exits, the
2185     detached process will continue to live.
2186
2187     Note that arguments that contain spaces are not passed to the
2188     process as separate arguments.
2189
2190     \bold{Unix:} The started process will run in its own session and act
2191     like a daemon.
2192
2193     \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
2194     The started process will run as a regular standalone process.
2195
2196     The process will be started in the directory \a workingDirectory.
2197
2198     If the function is successful then *\a pid is set to the process
2199     identifier of the started process.
2200 */
2201 bool QProcess::startDetached(const QString &program,
2202                              const QStringList &arguments,
2203                              const QString &workingDirectory,
2204                              qint64 *pid)
2205 {
2206     return QProcessPrivate::startDetached(program,
2207                                           arguments,
2208                                           workingDirectory,
2209                                           pid);
2210 }
2211
2212 /*!
2213     Starts the program \a program with the given \a arguments in a
2214     new process, and detaches from it. Returns true on success;
2215     otherwise returns false. If the calling process exits, the
2216     detached process will continue to live.
2217
2218     \note Arguments that contain spaces are not passed to the
2219     process as separate arguments.
2220
2221     \bold{Unix:} The started process will run in its own session and act
2222     like a daemon.
2223
2224     \bold{Windows:} Arguments that contain spaces are wrapped in quotes.
2225     The started process will run as a regular standalone process.
2226 */
2227 bool QProcess::startDetached(const QString &program,
2228                              const QStringList &arguments)
2229 {
2230     return QProcessPrivate::startDetached(program, arguments);
2231 }
2232
2233 /*!
2234     \overload
2235
2236     Starts the program \a program in a new process. \a program is a
2237     single string of text containing both the program name and its
2238     arguments. The arguments are separated by one or more spaces.
2239
2240     The \a program string can also contain quotes, to ensure that arguments
2241     containing spaces are correctly supplied to the new process.
2242 */
2243 bool QProcess::startDetached(const QString &program)
2244 {
2245     QStringList args = parseCombinedArgString(program);
2246     if (args.isEmpty())
2247         return false;
2248
2249     QString prog = args.first();
2250     args.removeFirst();
2251
2252     return QProcessPrivate::startDetached(prog, args);
2253 }
2254
2255 QT_BEGIN_INCLUDE_NAMESPACE
2256 #if defined(Q_OS_MAC) && !defined(QT_NO_CORESERVICES)
2257 # include <crt_externs.h>
2258 # define environ (*_NSGetEnviron())
2259 #elif defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN) || (defined(Q_OS_MAC) && defined(QT_NO_CORESERVICES))
2260   static char *qt_empty_environ[] = { 0 };
2261 #define environ qt_empty_environ
2262 #elif !defined(Q_OS_WIN)
2263   extern char **environ;
2264 #endif
2265 QT_END_INCLUDE_NAMESPACE
2266
2267 /*!
2268     \since 4.1
2269
2270     Returns the environment of the calling process as a list of
2271     key=value pairs. Example:
2272
2273     \snippet doc/src/snippets/code/src_corelib_io_qprocess.cpp 8
2274
2275     This function does not cache the system environment. Therefore, it's
2276     possible to obtain an updated version of the environment if low-level C
2277     library functions like \tt setenv ot \tt putenv have been called.
2278
2279     However, note that repeated calls to this function will recreate the
2280     list of environment variables, which is a non-trivial operation.
2281
2282     \note For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
2283
2284     \sa QProcessEnvironment::systemEnvironment(), environment(), setEnvironment()
2285 */
2286 QStringList QProcess::systemEnvironment()
2287 {
2288     QStringList tmp;
2289     char *entry = 0;
2290     int count = 0;
2291     while ((entry = environ[count++]))
2292         tmp << QString::fromLocal8Bit(entry);
2293     return tmp;
2294 }
2295
2296 /*!
2297     \fn QProcessEnvironment QProcessEnvironment::systemEnvironment()
2298
2299     \since 4.6
2300
2301     \brief The systemEnvironment function returns the environment of
2302     the calling process.
2303
2304     It is returned as a QProcessEnvironment. This function does not
2305     cache the system environment. Therefore, it's possible to obtain
2306     an updated version of the environment if low-level C library
2307     functions like \tt setenv ot \tt putenv have been called.
2308
2309     However, note that repeated calls to this function will recreate the
2310     QProcessEnvironment object, which is a non-trivial operation.
2311
2312     \sa QProcess::systemEnvironment()
2313 */
2314
2315 /*!
2316     \typedef Q_PID
2317     \relates QProcess
2318
2319     Typedef for the identifiers used to represent processes on the underlying
2320     platform. On Unix and Symbian, this corresponds to \l qint64; on Windows, it
2321     corresponds to \c{_PROCESS_INFORMATION*}.
2322
2323     \sa QProcess::pid()
2324 */
2325
2326 QT_END_NAMESPACE
2327
2328 #include "moc_qprocess.cpp"
2329
2330 #endif // QT_NO_PROCESS
2331