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