1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Copyright (C) 2016 Intel Corporation.
5 ** Contact: https://www.qt.io/licensing/
6 **
7 ** This file is part of the QtCore module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial License Usage
11 ** Licensees holding valid commercial Qt licenses may use this file in
12 ** accordance with the commercial license agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and The Qt Company. For licensing terms
15 ** and conditions see https://www.qt.io/terms-conditions. For further
16 ** information use the contact form at https://www.qt.io/contact-us.
17 **
18 ** GNU Lesser General Public License Usage
19 ** Alternatively, this file may be used under the terms of the GNU Lesser
20 ** General Public License version 3 as published by the Free Software
21 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
22 ** packaging of this file. Please review the following information to
23 ** ensure the GNU Lesser General Public License version 3 requirements
24 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25 **
26 ** GNU General Public License Usage
27 ** Alternatively, this file may be used under the terms of the GNU
28 ** General Public License version 2.0 or (at your option) the GNU General
29 ** Public license version 3 or any later version approved by the KDE Free
30 ** Qt Foundation. The licenses are as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32 ** included in the packaging of this file. Please review the following
33 ** information to ensure the GNU General Public License requirements will
34 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35 ** https://www.gnu.org/licenses/gpl-3.0.html.
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40 
41 //#define QPROCESS_DEBUG
42 
43 #include <qdebug.h>
44 #include <qdir.h>
45 #include <qscopedvaluerollback.h>
46 #if defined(Q_OS_WIN)
47 #include <qtimer.h>
48 #endif
49 #if defined QPROCESS_DEBUG
50 #include <qstring.h>
51 #include <ctype.h>
52 
53 QT_BEGIN_NAMESPACE
54 /*
55     Returns a human readable representation of the first \a len
56     characters in \a data.
57 */
qt_prettyDebug(const char * data,int len,int maxSize)58 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
59 {
60     if (!data) return "(null)";
61     QByteArray out;
62     for (int i = 0; i < len && i < maxSize; ++i) {
63         char c = data[i];
64         if (isprint(c)) {
65             out += c;
66         } else switch (c) {
67         case '\n': out += "\\n"; break;
68         case '\r': out += "\\r"; break;
69         case '\t': out += "\\t"; break;
70         default:
71             char buf[5];
72             qsnprintf(buf, sizeof(buf), "\\%3o", c);
73             buf[4] = '\0';
74             out += QByteArray(buf);
75         }
76     }
77 
78     if (len < maxSize)
79         out += "...";
80 
81     return out;
82 }
83 
84 QT_END_NAMESPACE
85 
86 #endif
87 
88 #include "qprocess.h"
89 #include "qprocess_p.h"
90 
91 #include <qbytearray.h>
92 #include <qelapsedtimer.h>
93 #include <qcoreapplication.h>
94 #include <qsocketnotifier.h>
95 #include <qtimer.h>
96 
97 #ifdef Q_OS_WIN
98 #include <qwineventnotifier.h>
99 #else
100 #include <private/qcore_unix_p.h>
101 #endif
102 
103 #if __has_include(<paths.h>)
104 #include <paths.h>
105 #endif
106 
107 QT_BEGIN_NAMESPACE
108 
109 /*!
110     \since 5.6
111 
112     \macro QT_NO_PROCESS_COMBINED_ARGUMENT_START
113     \relates QProcess
114 
115     Disables the
116     \l {QProcess::start(const QString &, QIODevice::OpenMode)}
117     {QProcess::start}() overload taking a single string.
118     In most cases where it is used, the user intends for the first argument
119     to be treated atomically as per the other overload.
120 
121     \sa QProcess::start(const QString &command, QIODevice::OpenMode mode)
122 */
123 
124 /*!
125     \class QProcessEnvironment
126     \inmodule QtCore
127 
128     \brief The QProcessEnvironment class holds the environment variables that
129     can be passed to a program.
130 
131     \ingroup io
132     \ingroup misc
133     \ingroup shared
134     \reentrant
135     \since 4.6
136 
137     A process's environment is composed of a set of key=value pairs known as
138     environment variables. The QProcessEnvironment class wraps that concept
139     and allows easy manipulation of those variables. It's meant to be used
140     along with QProcess, to set the environment for child processes. It
141     cannot be used to change the current process's environment.
142 
143     The environment of the calling process can be obtained using
144     QProcessEnvironment::systemEnvironment().
145 
146     On Unix systems, the variable names are case-sensitive. Note that the
147     Unix environment allows both variable names and contents to contain arbitrary
148     binary data (except for the NUL character). QProcessEnvironment will preserve
149     such variables, but does not support manipulating variables whose names or
150     values cannot be encoded by the current locale settings (see
151     QTextCodec::codecForLocale).
152 
153     On Windows, the variable names are case-insensitive, but case-preserving.
154     QProcessEnvironment behaves accordingly.
155 
156     \sa QProcess, QProcess::systemEnvironment(), QProcess::setProcessEnvironment()
157 */
158 
toList() const159 QStringList QProcessEnvironmentPrivate::toList() const
160 {
161     QStringList result;
162     result.reserve(vars.size());
163     for (auto it = vars.cbegin(), end = vars.cend(); it != end; ++it)
164         result << nameToString(it.key()) + QLatin1Char('=') + valueToString(it.value());
165     return result;
166 }
167 
fromList(const QStringList & list)168 QProcessEnvironment QProcessEnvironmentPrivate::fromList(const QStringList &list)
169 {
170     QProcessEnvironment env;
171     QStringList::ConstIterator it = list.constBegin(),
172                               end = list.constEnd();
173     for ( ; it != end; ++it) {
174         int pos = it->indexOf(QLatin1Char('='), 1);
175         if (pos < 1)
176             continue;
177 
178         QString value = it->mid(pos + 1);
179         QString name = *it;
180         name.truncate(pos);
181         env.insert(name, value);
182     }
183     return env;
184 }
185 
keys() const186 QStringList QProcessEnvironmentPrivate::keys() const
187 {
188     QStringList result;
189     result.reserve(vars.size());
190     auto it = vars.constBegin();
191     const auto end = vars.constEnd();
192     for ( ; it != end; ++it)
193         result << nameToString(it.key());
194     return result;
195 }
196 
insert(const QProcessEnvironmentPrivate & other)197 void QProcessEnvironmentPrivate::insert(const QProcessEnvironmentPrivate &other)
198 {
199     auto it = other.vars.constBegin();
200     const auto end = other.vars.constEnd();
201     for ( ; it != end; ++it)
202         vars.insert(it.key(), it.value());
203 
204 #ifdef Q_OS_UNIX
205     const OrderedNameMapMutexLocker locker(this, &other);
206     auto nit = other.nameMap.constBegin();
207     const auto nend = other.nameMap.constEnd();
208     for ( ; nit != nend; ++nit)
209         nameMap.insert(nit.key(), nit.value());
210 #endif
211 }
212 
213 /*!
214     Creates a new QProcessEnvironment object. This constructor creates an
215     empty environment. If set on a QProcess, this will cause the current
216     environment variables to be removed.
217 */
QProcessEnvironment()218 QProcessEnvironment::QProcessEnvironment()
219     : d(nullptr)
220 {
221 }
222 
223 /*!
224     Frees the resources associated with this QProcessEnvironment object.
225 */
~QProcessEnvironment()226 QProcessEnvironment::~QProcessEnvironment()
227 {
228 }
229 
230 /*!
231     Creates a QProcessEnvironment object that is a copy of \a other.
232 */
QProcessEnvironment(const QProcessEnvironment & other)233 QProcessEnvironment::QProcessEnvironment(const QProcessEnvironment &other)
234     : d(other.d)
235 {
236 }
237 
238 /*!
239     Copies the contents of the \a other QProcessEnvironment object into this
240     one.
241 */
operator =(const QProcessEnvironment & other)242 QProcessEnvironment &QProcessEnvironment::operator=(const QProcessEnvironment &other)
243 {
244     d = other.d;
245     return *this;
246 }
247 
248 /*!
249     \fn void QProcessEnvironment::swap(QProcessEnvironment &other)
250     \since 5.0
251 
252     Swaps this process environment instance with \a other. This
253     function is very fast and never fails.
254 */
255 
256 /*!
257     \fn bool QProcessEnvironment::operator !=(const QProcessEnvironment &other) const
258 
259     Returns \c true if this and the \a other QProcessEnvironment objects are different.
260 
261     \sa operator==()
262 */
263 
264 /*!
265     Returns \c true if this and the \a other QProcessEnvironment objects are equal.
266 
267     Two QProcessEnvironment objects are considered equal if they have the same
268     set of key=value pairs. The comparison of keys is done case-sensitive on
269     platforms where the environment is case-sensitive.
270 
271     \sa operator!=(), contains()
272 */
operator ==(const QProcessEnvironment & other) const273 bool QProcessEnvironment::operator==(const QProcessEnvironment &other) const
274 {
275     if (d == other.d)
276         return true;
277     if (d) {
278         if (other.d) {
279             return d->vars == other.d->vars;
280         } else {
281             return isEmpty();
282         }
283     } else {
284         return other.isEmpty();
285     }
286 }
287 
288 /*!
289     Returns \c true if this QProcessEnvironment object is empty: that is
290     there are no key=value pairs set.
291 
292     \sa clear(), systemEnvironment(), insert()
293 */
isEmpty() const294 bool QProcessEnvironment::isEmpty() const
295 {
296     // Needs no locking, as no hash nodes are accessed
297     return d ? d->vars.isEmpty() : true;
298 }
299 
300 /*!
301     Removes all key=value pairs from this QProcessEnvironment object, making
302     it empty.
303 
304     \sa isEmpty(), systemEnvironment()
305 */
clear()306 void QProcessEnvironment::clear()
307 {
308     if (d)
309         d->vars.clear();
310     // Unix: Don't clear d->nameMap, as the environment is likely to be
311     // re-populated with the same keys again.
312 }
313 
314 /*!
315     Returns \c true if the environment variable of name \a name is found in
316     this QProcessEnvironment object.
317 
318 
319     \sa insert(), value()
320 */
contains(const QString & name) const321 bool QProcessEnvironment::contains(const QString &name) const
322 {
323     if (!d)
324         return false;
325     return d->vars.contains(d->prepareName(name));
326 }
327 
328 /*!
329     Inserts the environment variable of name \a name and contents \a value
330     into this QProcessEnvironment object. If that variable already existed,
331     it is replaced by the new value.
332 
333     On most systems, inserting a variable with no contents will have the
334     same effect for applications as if the variable had not been set at all.
335     However, to guarantee that there are no incompatibilities, to remove a
336     variable, please use the remove() function.
337 
338     \sa contains(), remove(), value()
339 */
insert(const QString & name,const QString & value)340 void QProcessEnvironment::insert(const QString &name, const QString &value)
341 {
342     // our re-impl of detach() detaches from null
343     d.detach(); // detach before prepareName()
344     d->vars.insert(d->prepareName(name), d->prepareValue(value));
345 }
346 
347 /*!
348     Removes the environment variable identified by \a name from this
349     QProcessEnvironment object. If that variable did not exist before,
350     nothing happens.
351 
352 
353     \sa contains(), insert(), value()
354 */
remove(const QString & name)355 void QProcessEnvironment::remove(const QString &name)
356 {
357     if (d) {
358         d.detach(); // detach before prepareName()
359         d->vars.remove(d->prepareName(name));
360     }
361 }
362 
363 /*!
364     Searches this QProcessEnvironment object for a variable identified by
365     \a name and returns its value. If the variable is not found in this object,
366     then \a defaultValue is returned instead.
367 
368     \sa contains(), insert(), remove()
369 */
value(const QString & name,const QString & defaultValue) const370 QString QProcessEnvironment::value(const QString &name, const QString &defaultValue) const
371 {
372     if (!d)
373         return defaultValue;
374 
375     const auto it = d->vars.constFind(d->prepareName(name));
376     if (it == d->vars.constEnd())
377         return defaultValue;
378 
379     return d->valueToString(it.value());
380 }
381 
382 /*!
383     Converts this QProcessEnvironment object into a list of strings, one for
384     each environment variable that is set. The environment variable's name
385     and its value are separated by an equal character ('=').
386 
387     The QStringList contents returned by this function are suitable for
388     presentation.
389     Use with the QProcess::setEnvironment function is not recommended due to
390     potential encoding problems under Unix, and worse performance.
391 
392     \sa systemEnvironment(), QProcess::systemEnvironment(),
393         QProcess::setProcessEnvironment()
394 */
toStringList() const395 QStringList QProcessEnvironment::toStringList() const
396 {
397     if (!d)
398         return QStringList();
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     return d->keys();
413 }
414 
415 /*!
416     \overload
417     \since 4.8
418 
419     Inserts the contents of \a e in this QProcessEnvironment object. Variables in
420     this object that also exist in \a e will be overwritten.
421 */
insert(const QProcessEnvironment & e)422 void QProcessEnvironment::insert(const QProcessEnvironment &e)
423 {
424     if (!e.d)
425         return;
426 
427     // our re-impl of detach() detaches from null
428     d->insert(*e.d);
429 }
430 
431 #if QT_CONFIG(process)
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 = nullptr;
440         break;
441     case PipeSink:
442         Q_ASSERT(process);
443         process->stdoutChannel.type = Normal;
444         process->stdoutChannel.process = nullptr;
445         break;
446     }
447 
448     type = Normal;
449     file.clear();
450     process = nullptr;
451 }
452 
453 /*!
454     \class QProcess
455     \inmodule QtCore
456 
457     \brief The QProcess class is used to start external programs and
458     to communicate with them.
459 
460     \ingroup io
461 
462     \reentrant
463 
464     \section1 Running a Process
465 
466     To start a process, pass the name and command line arguments of
467     the program you want to run as arguments to start(). Arguments
468     are supplied as individual strings in a QStringList.
469 
470     Alternatively, you can set the program to run with setProgram()
471     and setArguments(), and then call start() or open().
472 
473     For example, the following code snippet runs the analog clock
474     example in the Fusion style on X11 platforms by passing strings
475     containing "-style" and "fusion" as two items in the list of
476     arguments:
477 
478     \snippet qprocess/qprocess-simpleexecution.cpp 0
479     \dots
480     \snippet qprocess/qprocess-simpleexecution.cpp 1
481     \snippet qprocess/qprocess-simpleexecution.cpp 2
482 
483     QProcess then enters the \l Starting state, and when the program
484     has started, QProcess enters the \l Running state and emits
485     started().
486 
487     QProcess allows you to treat a process as a sequential I/O
488     device. You can write to and read from the process just as you
489     would access a network connection using QTcpSocket. You can then
490     write to the process's standard input by calling write(), and
491     read the standard output by calling read(), readLine(), and
492     getChar(). Because it inherits QIODevice, QProcess can also be
493     used as an input source for QXmlReader, or for generating data to
494     be uploaded using QNetworkAccessManager.
495 
496     When the process exits, QProcess reenters the \l NotRunning state
497     (the initial state), and emits finished().
498 
499     The finished() signal provides the exit code and exit status of
500     the process as arguments, and you can also call exitCode() to
501     obtain the exit code of the last process that finished, and
502     exitStatus() to obtain its exit status. If an error occurs at
503     any point in time, QProcess will emit the errorOccurred() signal.
504     You can also call error() to find the type of error that occurred
505     last, and state() to find the current process state.
506 
507     \note QProcess is not supported on VxWorks, iOS, tvOS, watchOS,
508     or the Universal Windows Platform.
509 
510     \section1 Communicating via Channels
511 
512     Processes have two predefined output channels: The standard
513     output channel (\c stdout) supplies regular console output, and
514     the standard error channel (\c stderr) usually supplies the
515     errors that are printed by the process. These channels represent
516     two separate streams of data. You can toggle between them by
517     calling setReadChannel(). QProcess emits readyRead() when data is
518     available on the current read channel. It also emits
519     readyReadStandardOutput() when new standard output data is
520     available, and when new standard error data is available,
521     readyReadStandardError() is emitted. Instead of calling read(),
522     readLine(), or getChar(), you can explicitly read all data from
523     either of the two channels by calling readAllStandardOutput() or
524     readAllStandardError().
525 
526     The terminology for the channels can be misleading. Be aware that
527     the process's output channels correspond to QProcess's
528     \e read channels, whereas the process's input channels correspond
529     to QProcess's \e write channels. This is because what we read
530     using QProcess is the process's output, and what we write becomes
531     the process's input.
532 
533     QProcess can merge the two output channels, so that standard
534     output and standard error data from the running process both use
535     the standard output channel. Call setProcessChannelMode() with
536     MergedChannels before starting the process to activate
537     this feature. You also have the option of forwarding the output of
538     the running process to the calling, main process, by passing
539     ForwardedChannels as the argument. It is also possible to forward
540     only one of the output channels - typically one would use
541     ForwardedErrorChannel, but ForwardedOutputChannel also exists.
542     Note that using channel forwarding is typically a bad idea in GUI
543     applications - you should present errors graphically instead.
544 
545     Certain processes need special environment settings in order to
546     operate. You can set environment variables for your process by
547     calling setProcessEnvironment(). To set a working directory, call
548     setWorkingDirectory(). By default, processes are run in the
549     current working directory of the calling process.
550 
551     The positioning and the screen Z-order of windows belonging to
552     GUI applications started with QProcess are controlled by
553     the underlying windowing system. For Qt 5 applications, the
554     positioning can be specified using the \c{-qwindowgeometry}
555     command line option; X11 applications generally accept a
556     \c{-geometry} command line option.
557 
558     \note On QNX, setting the working directory may cause all
559     application threads, with the exception of the QProcess caller
560     thread, to temporarily freeze during the spawning process,
561     owing to a limitation in the operating system.
562 
563     \section1 Synchronous Process API
564 
565     QProcess provides a set of functions which allow it to be used
566     without an event loop, by suspending the calling thread until
567     certain signals are emitted:
568 
569     \list
570     \li waitForStarted() blocks until the process has started.
571 
572     \li waitForReadyRead() blocks until new data is
573     available for reading on the current read channel.
574 
575     \li waitForBytesWritten() blocks until one payload of
576     data has been written to the process.
577 
578     \li waitForFinished() blocks until the process has finished.
579     \endlist
580 
581     Calling these functions from the main thread (the thread that
582     calls QApplication::exec()) may cause your user interface to
583     freeze.
584 
585     The following example runs \c gzip to compress the string "Qt
586     rocks!", without an event loop:
587 
588     \snippet process/process.cpp 0
589 
590     \section1 Notes for Windows Users
591 
592     Some Windows commands (for example, \c dir) are not provided by
593     separate applications, but by the command interpreter itself.
594     If you attempt to use QProcess to execute these commands directly,
595     it won't work. One possible solution is to execute the command
596     interpreter itself (\c{cmd.exe} on some Windows systems), and ask
597     the interpreter to execute the desired command.
598 
599     \sa QBuffer, QFile, QTcpSocket
600 */
601 
602 /*!
603     \enum QProcess::ProcessChannel
604 
605     This enum describes the process channels used by the running process.
606     Pass one of these values to setReadChannel() to set the
607     current read channel of QProcess.
608 
609     \value StandardOutput The standard output (stdout) of the running
610            process.
611 
612     \value StandardError The standard error (stderr) of the running
613            process.
614 
615     \sa setReadChannel()
616 */
617 
618 /*!
619     \enum QProcess::ProcessChannelMode
620 
621     This enum describes the process output channel modes of QProcess.
622     Pass one of these values to setProcessChannelMode() to set the
623     current read channel mode.
624 
625     \value SeparateChannels QProcess manages the output of the
626     running process, keeping standard output and standard error data
627     in separate internal buffers. You can select the QProcess's
628     current read channel by calling setReadChannel(). This is the
629     default channel mode of QProcess.
630 
631     \value MergedChannels QProcess merges the output of the running
632     process into the standard output channel (\c stdout). The
633     standard error channel (\c stderr) will not receive any data. The
634     standard output and standard error data of the running process
635     are interleaved.
636 
637     \value ForwardedChannels QProcess forwards the output of the
638     running process onto the main process. Anything the child process
639     writes to its standard output and standard error will be written
640     to the standard output and standard error of the main process.
641 
642     \value ForwardedErrorChannel QProcess manages the standard output
643     of the running process, but forwards its standard error onto the
644     main process. This reflects the typical use of command line tools
645     as filters, where the standard output is redirected to another
646     process or a file, while standard error is printed to the console
647     for diagnostic purposes.
648     (This value was introduced in Qt 5.2.)
649 
650     \value ForwardedOutputChannel Complementary to ForwardedErrorChannel.
651     (This value was introduced in Qt 5.2.)
652 
653     \note Windows intentionally suppresses output from GUI-only
654     applications to inherited consoles.
655     This does \e not apply to output redirected to files or pipes.
656     To forward the output of GUI-only applications on the console
657     nonetheless, you must use SeparateChannels and do the forwarding
658     yourself by reading the output and writing it to the appropriate
659     output channels.
660 
661     \sa setProcessChannelMode()
662 */
663 
664 /*!
665     \enum QProcess::InputChannelMode
666     \since 5.2
667 
668     This enum describes the process input channel modes of QProcess.
669     Pass one of these values to setInputChannelMode() to set the
670     current write channel mode.
671 
672     \value ManagedInputChannel QProcess manages the input of the running
673     process. This is the default input channel mode of QProcess.
674 
675     \value ForwardedInputChannel QProcess forwards the input of the main
676     process onto the running process. The child process reads its standard
677     input from the same source as the main process.
678     Note that the main process must not try to read its standard input
679     while the child process is running.
680 
681     \sa setInputChannelMode()
682 */
683 
684 /*!
685     \enum QProcess::ProcessError
686 
687     This enum describes the different types of errors that are
688     reported by QProcess.
689 
690     \value FailedToStart The process failed to start. Either the
691     invoked program is missing, or you may have insufficient
692     permissions to invoke the program.
693 
694     \value Crashed The process crashed some time after starting
695     successfully.
696 
697     \value Timedout The last waitFor...() function timed out. The
698     state of QProcess is unchanged, and you can try calling
699     waitFor...() again.
700 
701     \value WriteError An error occurred when attempting to write to the
702     process. For example, the process may not be running, or it may
703     have closed its input channel.
704 
705     \value ReadError An error occurred when attempting to read from
706     the process. For example, the process may not be running.
707 
708     \value UnknownError An unknown error occurred. This is the default
709     return value of error().
710 
711     \sa error()
712 */
713 
714 /*!
715     \enum QProcess::ProcessState
716 
717     This enum describes the different states of QProcess.
718 
719     \value NotRunning The process is not running.
720 
721     \value Starting The process is starting, but the program has not
722     yet been invoked.
723 
724     \value Running The process is running and is ready for reading and
725     writing.
726 
727     \sa state()
728 */
729 
730 /*!
731     \enum QProcess::ExitStatus
732 
733     This enum describes the different exit statuses of QProcess.
734 
735     \value NormalExit The process exited normally.
736 
737     \value CrashExit The process crashed.
738 
739     \sa exitStatus()
740 */
741 
742 /*!
743     \typedef QProcess::CreateProcessArgumentModifier
744     \note This typedef is only available on desktop Windows.
745 
746     On Windows, QProcess uses the Win32 API function \c CreateProcess to
747     start child processes. While QProcess provides a comfortable way to start
748     processes without worrying about platform
749     details, it is in some cases desirable to fine-tune the parameters that are
750     passed to \c CreateProcess. This is done by defining a
751     \c CreateProcessArgumentModifier function and passing it to
752     \c setCreateProcessArgumentsModifier.
753 
754     A \c CreateProcessArgumentModifier function takes one parameter: a pointer
755     to a \c CreateProcessArguments struct. The members of this struct will be
756     passed to \c CreateProcess after the \c CreateProcessArgumentModifier
757     function is called.
758 
759     The following example demonstrates how to pass custom flags to
760     \c CreateProcess.
761     When starting a console process B from a console process A, QProcess will
762     reuse the console window of process A for process B by default. In this
763     example, a new console window with a custom color scheme is created for the
764     child process B instead.
765 
766     \snippet qprocess/qprocess-createprocessargumentsmodifier.cpp 0
767 
768     \sa QProcess::CreateProcessArguments
769     \sa setCreateProcessArgumentsModifier()
770 */
771 
772 /*!
773     \class QProcess::CreateProcessArguments
774     \inmodule QtCore
775     \note This struct is only available on the Windows platform.
776 
777     This struct is a representation of all parameters of the Windows API
778     function \c CreateProcess. It is used as parameter for
779     \c CreateProcessArgumentModifier functions.
780 
781     \sa QProcess::CreateProcessArgumentModifier
782 */
783 
784 /*!
785     \fn void QProcess::error(QProcess::ProcessError error)
786     \obsolete
787 
788     Use errorOccurred() instead.
789 */
790 
791 /*!
792     \fn void QProcess::errorOccurred(QProcess::ProcessError error)
793     \since 5.6
794 
795     This signal is emitted when an error occurs with the process. The
796     specified \a error describes the type of error that occurred.
797 */
798 
799 /*!
800     \fn void QProcess::started()
801 
802     This signal is emitted by QProcess when the process has started,
803     and state() returns \l Running.
804 */
805 
806 /*!
807     \fn void QProcess::stateChanged(QProcess::ProcessState newState)
808 
809     This signal is emitted whenever the state of QProcess changes. The
810     \a newState argument is the state QProcess changed to.
811 */
812 
813 #if QT_DEPRECATED_SINCE(5, 13)
814 /*!
815     \fn void QProcess::finished(int exitCode)
816     \obsolete
817     \overload
818 
819     Use finished(int exitCode, QProcess::ExitStatus status) instead.
820 */
821 #endif
822 
823 /*!
824     \fn void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus)
825 
826     This signal is emitted when the process finishes. \a exitCode is the exit
827     code of the process (only valid for normal exits), and \a exitStatus is
828     the exit status.
829     After the process has finished, the buffers in QProcess are still intact.
830     You can still read any data that the process may have written before it
831     finished.
832 
833     \sa exitStatus()
834 */
835 
836 /*!
837     \fn void QProcess::readyReadStandardOutput()
838 
839     This signal is emitted when the process has made new data
840     available through its standard output channel (\c stdout). It is
841     emitted regardless of the current \l{readChannel()}{read channel}.
842 
843     \sa readAllStandardOutput(), readChannel()
844 */
845 
846 /*!
847     \fn void QProcess::readyReadStandardError()
848 
849     This signal is emitted when the process has made new data
850     available through its standard error channel (\c stderr). It is
851     emitted regardless of the current \l{readChannel()}{read
852     channel}.
853 
854     \sa readAllStandardError(), readChannel()
855 */
856 
857 /*!
858     \internal
859 */
QProcessPrivate()860 QProcessPrivate::QProcessPrivate()
861 {
862     readBufferChunkSize = QRINGBUFFER_CHUNKSIZE;
863     writeBufferChunkSize = QRINGBUFFER_CHUNKSIZE;
864     processChannelMode = QProcess::SeparateChannels;
865     inputChannelMode = QProcess::ManagedInputChannel;
866     processError = QProcess::UnknownError;
867     processState = QProcess::NotRunning;
868     pid = 0;
869     sequenceNumber = 0;
870     exitCode = 0;
871     exitStatus = QProcess::NormalExit;
872     startupSocketNotifier = nullptr;
873     deathNotifier = nullptr;
874     childStartedPipe[0] = INVALID_Q_PIPE;
875     childStartedPipe[1] = INVALID_Q_PIPE;
876     forkfd = -1;
877     crashed = false;
878     dying = false;
879     emittedReadyRead = false;
880     emittedBytesWritten = false;
881 #ifdef Q_OS_WIN
882     stdinWriteTrigger = 0;
883     processFinishedNotifier = 0;
884 #endif // Q_OS_WIN
885 }
886 
887 /*!
888     \internal
889 */
~QProcessPrivate()890 QProcessPrivate::~QProcessPrivate()
891 {
892     if (stdinChannel.process)
893         stdinChannel.process->stdoutChannel.clear();
894     if (stdoutChannel.process)
895         stdoutChannel.process->stdinChannel.clear();
896 }
897 
898 /*!
899     \internal
900 */
cleanup()901 void QProcessPrivate::cleanup()
902 {
903     q_func()->setProcessState(QProcess::NotRunning);
904 #ifdef Q_OS_WIN
905     if (pid) {
906         CloseHandle(pid->hThread);
907         CloseHandle(pid->hProcess);
908         delete pid;
909         pid = 0;
910     }
911     if (stdinWriteTrigger) {
912         delete stdinWriteTrigger;
913         stdinWriteTrigger = 0;
914     }
915     if (processFinishedNotifier) {
916         delete processFinishedNotifier;
917         processFinishedNotifier = 0;
918     }
919 
920 #endif
921     pid = 0;
922     sequenceNumber = 0;
923     dying = false;
924 
925     if (stdoutChannel.notifier) {
926         delete stdoutChannel.notifier;
927         stdoutChannel.notifier = nullptr;
928     }
929     if (stderrChannel.notifier) {
930         delete stderrChannel.notifier;
931         stderrChannel.notifier = nullptr;
932     }
933     if (stdinChannel.notifier) {
934         delete stdinChannel.notifier;
935         stdinChannel.notifier = nullptr;
936     }
937     if (startupSocketNotifier) {
938         delete startupSocketNotifier;
939         startupSocketNotifier = nullptr;
940     }
941     if (deathNotifier) {
942         delete deathNotifier;
943         deathNotifier = nullptr;
944     }
945     closeChannel(&stdoutChannel);
946     closeChannel(&stderrChannel);
947     closeChannel(&stdinChannel);
948     destroyPipe(childStartedPipe);
949 #ifdef Q_OS_UNIX
950     if (forkfd != -1)
951         qt_safe_close(forkfd);
952     forkfd = -1;
953 #endif
954 }
955 
956 /*!
957     \internal
958 */
setError(QProcess::ProcessError error,const QString & description)959 void QProcessPrivate::setError(QProcess::ProcessError error, const QString &description)
960 {
961     processError = error;
962     if (description.isEmpty()) {
963         switch (error) {
964         case QProcess::FailedToStart:
965             errorString = QProcess::tr("Process failed to start");
966             break;
967         case QProcess::Crashed:
968             errorString = QProcess::tr("Process crashed");
969             break;
970         case QProcess::Timedout:
971             errorString = QProcess::tr("Process operation timed out");
972             break;
973         case QProcess::ReadError:
974             errorString = QProcess::tr("Error reading from process");
975             break;
976         case QProcess::WriteError:
977             errorString = QProcess::tr("Error writing to process");
978             break;
979         case QProcess::UnknownError:
980             errorString.clear();
981             break;
982         }
983     } else {
984         errorString = description;
985     }
986 }
987 
988 /*!
989     \internal
990 */
setErrorAndEmit(QProcess::ProcessError error,const QString & description)991 void QProcessPrivate::setErrorAndEmit(QProcess::ProcessError error, const QString &description)
992 {
993     Q_Q(QProcess);
994     Q_ASSERT(error != QProcess::UnknownError);
995     setError(error, description);
996     emit q->errorOccurred(processError);
997 #if QT_DEPRECATED_SINCE(5, 6)
998 QT_WARNING_PUSH
999 QT_WARNING_DISABLE_DEPRECATED
1000     emit q->error(processError);
1001 QT_WARNING_POP
1002 #endif
1003 }
1004 
1005 /*!
1006     \internal
1007     Returns \c true if we emitted readyRead().
1008 */
tryReadFromChannel(Channel * channel)1009 bool QProcessPrivate::tryReadFromChannel(Channel *channel)
1010 {
1011     Q_Q(QProcess);
1012     if (channel->pipe[0] == INVALID_Q_PIPE)
1013         return false;
1014 
1015     qint64 available = bytesAvailableInChannel(channel);
1016     if (available == 0)
1017         available = 1;      // always try to read at least one byte
1018 
1019     QProcess::ProcessChannel channelIdx = (channel == &stdoutChannel
1020                                            ? QProcess::StandardOutput
1021                                            : QProcess::StandardError);
1022     Q_ASSERT(readBuffers.size() > int(channelIdx));
1023     QRingBuffer &readBuffer = readBuffers[int(channelIdx)];
1024     char *ptr = readBuffer.reserve(available);
1025     qint64 readBytes = readFromChannel(channel, ptr, available);
1026     if (readBytes <= 0)
1027         readBuffer.chop(available);
1028     if (readBytes == -2) {
1029         // EWOULDBLOCK
1030         return false;
1031     }
1032     if (readBytes == -1) {
1033         setErrorAndEmit(QProcess::ReadError);
1034 #if defined QPROCESS_DEBUG
1035         qDebug("QProcessPrivate::tryReadFromChannel(%d), failed to read from the process",
1036                int(channel - &stdinChannel));
1037 #endif
1038         return false;
1039     }
1040     if (readBytes == 0) {
1041         // EOF
1042         if (channel->notifier)
1043             channel->notifier->setEnabled(false);
1044         closeChannel(channel);
1045 #if defined QPROCESS_DEBUG
1046         qDebug("QProcessPrivate::tryReadFromChannel(%d), 0 bytes available",
1047                int(channel - &stdinChannel));
1048 #endif
1049         return false;
1050     }
1051 #if defined QPROCESS_DEBUG
1052     qDebug("QProcessPrivate::tryReadFromChannel(%d), read %lld bytes from the process' output",
1053            int(channel - &stdinChannel), readBytes);
1054 #endif
1055 
1056     if (channel->closed) {
1057         readBuffer.chop(readBytes);
1058         return false;
1059     }
1060 
1061     readBuffer.chop(available - readBytes);
1062 
1063     bool didRead = false;
1064     if (currentReadChannel == channelIdx) {
1065         didRead = true;
1066         if (!emittedReadyRead) {
1067             QScopedValueRollback<bool> guard(emittedReadyRead, true);
1068             emit q->readyRead();
1069         }
1070     }
1071     emit q->channelReadyRead(int(channelIdx));
1072     if (channelIdx == QProcess::StandardOutput)
1073         emit q->readyReadStandardOutput(QProcess::QPrivateSignal());
1074     else
1075         emit q->readyReadStandardError(QProcess::QPrivateSignal());
1076     return didRead;
1077 }
1078 
1079 /*!
1080     \internal
1081 */
_q_canReadStandardOutput()1082 bool QProcessPrivate::_q_canReadStandardOutput()
1083 {
1084     return tryReadFromChannel(&stdoutChannel);
1085 }
1086 
1087 /*!
1088     \internal
1089 */
_q_canReadStandardError()1090 bool QProcessPrivate::_q_canReadStandardError()
1091 {
1092     return tryReadFromChannel(&stderrChannel);
1093 }
1094 
1095 /*!
1096     \internal
1097 */
_q_canWrite()1098 bool QProcessPrivate::_q_canWrite()
1099 {
1100     if (writeBuffer.isEmpty()) {
1101         if (stdinChannel.notifier)
1102             stdinChannel.notifier->setEnabled(false);
1103 #if defined QPROCESS_DEBUG
1104         qDebug("QProcessPrivate::canWrite(), not writing anything (empty write buffer).");
1105 #endif
1106         return false;
1107     }
1108 
1109     const bool writeSucceeded = writeToStdin();
1110 
1111     if (writeBuffer.isEmpty() && stdinChannel.closed)
1112         closeWriteChannel();
1113     else if (stdinChannel.notifier)
1114         stdinChannel.notifier->setEnabled(!writeBuffer.isEmpty());
1115     return writeSucceeded;
1116 }
1117 
1118 /*!
1119     \internal
1120 */
_q_processDied()1121 bool QProcessPrivate::_q_processDied()
1122 {
1123     Q_Q(QProcess);
1124 #if defined QPROCESS_DEBUG
1125     qDebug("QProcessPrivate::_q_processDied()");
1126 #endif
1127 #ifdef Q_OS_UNIX
1128     if (!waitForDeadChild())
1129         return false;
1130 #endif
1131 #ifdef Q_OS_WIN
1132     if (processFinishedNotifier)
1133         processFinishedNotifier->setEnabled(false);
1134     drainOutputPipes();
1135 #endif
1136 
1137     // the process may have died before it got a chance to report that it was
1138     // either running or stopped, so we will call _q_startupNotification() and
1139     // give it a chance to emit started() or errorOccurred(FailedToStart).
1140     if (processState == QProcess::Starting) {
1141         if (!_q_startupNotification())
1142             return true;
1143     }
1144 
1145     if (dying) {
1146         // at this point we know the process is dead. prevent
1147         // reentering this slot recursively by calling waitForFinished()
1148         // or opening a dialog inside slots connected to the readyRead
1149         // signals emitted below.
1150         return true;
1151     }
1152     dying = true;
1153 
1154     // in case there is data in the pipe line and this slot by chance
1155     // got called before the read notifications, call these two slots
1156     // so the data is made available before the process dies.
1157     _q_canReadStandardOutput();
1158     _q_canReadStandardError();
1159 
1160     findExitCode();
1161 
1162     if (crashed) {
1163         exitStatus = QProcess::CrashExit;
1164         setErrorAndEmit(QProcess::Crashed);
1165     }
1166 
1167     bool wasRunning = (processState == QProcess::Running);
1168 
1169     cleanup();
1170 
1171     if (wasRunning) {
1172         // we received EOF now:
1173         emit q->readChannelFinished();
1174         // in the future:
1175         //emit q->standardOutputClosed();
1176         //emit q->standardErrorClosed();
1177 
1178 #if QT_DEPRECATED_SINCE(5, 13)
1179 QT_WARNING_PUSH
1180 QT_WARNING_DISABLE_DEPRECATED
1181         emit q->finished(exitCode);
1182 QT_WARNING_POP
1183 #endif
1184         emit q->finished(exitCode, exitStatus);
1185     }
1186 #if defined QPROCESS_DEBUG
1187     qDebug("QProcessPrivate::_q_processDied() process is dead");
1188 #endif
1189     return true;
1190 }
1191 
1192 /*!
1193     \internal
1194 */
_q_startupNotification()1195 bool QProcessPrivate::_q_startupNotification()
1196 {
1197     Q_Q(QProcess);
1198 #if defined QPROCESS_DEBUG
1199     qDebug("QProcessPrivate::startupNotification()");
1200 #endif
1201 
1202     if (startupSocketNotifier)
1203         startupSocketNotifier->setEnabled(false);
1204     QString errorMessage;
1205     if (processStarted(&errorMessage)) {
1206         q->setProcessState(QProcess::Running);
1207         emit q->started(QProcess::QPrivateSignal());
1208         return true;
1209     }
1210 
1211     q->setProcessState(QProcess::NotRunning);
1212     setErrorAndEmit(QProcess::FailedToStart, errorMessage);
1213 #ifdef Q_OS_UNIX
1214     // make sure the process manager removes this entry
1215     waitForDeadChild();
1216     findExitCode();
1217 #endif
1218     cleanup();
1219     return false;
1220 }
1221 
1222 /*!
1223     \internal
1224 */
closeWriteChannel()1225 void QProcessPrivate::closeWriteChannel()
1226 {
1227 #if defined QPROCESS_DEBUG
1228     qDebug("QProcessPrivate::closeWriteChannel()");
1229 #endif
1230     if (stdinChannel.notifier) {
1231         delete stdinChannel.notifier;
1232         stdinChannel.notifier = nullptr;
1233     }
1234 #ifdef Q_OS_WIN
1235     // ### Find a better fix, feeding the process little by little
1236     // instead.
1237     flushPipeWriter();
1238 #endif
1239     closeChannel(&stdinChannel);
1240 }
1241 
1242 /*!
1243     Constructs a QProcess object with the given \a parent.
1244 */
QProcess(QObject * parent)1245 QProcess::QProcess(QObject *parent)
1246     : QIODevice(*new QProcessPrivate, parent)
1247 {
1248 #if defined QPROCESS_DEBUG
1249     qDebug("QProcess::QProcess(%p)", parent);
1250 #endif
1251 }
1252 
1253 /*!
1254     Destructs the QProcess object, i.e., killing the process.
1255 
1256     Note that this function will not return until the process is
1257     terminated.
1258 */
~QProcess()1259 QProcess::~QProcess()
1260 {
1261     Q_D(QProcess);
1262     if (d->processState != NotRunning) {
1263         qWarning().nospace()
1264             << "QProcess: Destroyed while process (" << QDir::toNativeSeparators(program()) << ") is still running.";
1265         kill();
1266         waitForFinished();
1267     }
1268 #ifdef Q_OS_UNIX
1269     // make sure the process manager removes this entry
1270     d->findExitCode();
1271 #endif
1272     d->cleanup();
1273 }
1274 
1275 #if QT_DEPRECATED_SINCE(5, 13)
1276 /*!
1277     \obsolete
1278     Returns the read channel mode of the QProcess. This function is
1279     equivalent to processChannelMode()
1280 
1281     \sa processChannelMode()
1282 */
readChannelMode() const1283 QProcess::ProcessChannelMode QProcess::readChannelMode() const
1284 {
1285     return processChannelMode();
1286 }
1287 
1288 /*!
1289     \obsolete
1290 
1291     Use setProcessChannelMode(\a mode) instead.
1292 
1293     \sa setProcessChannelMode()
1294 */
setReadChannelMode(ProcessChannelMode mode)1295 void QProcess::setReadChannelMode(ProcessChannelMode mode)
1296 {
1297     setProcessChannelMode(mode);
1298 }
1299 #endif
1300 
1301 /*!
1302     \since 4.2
1303 
1304     Returns the channel mode of the QProcess standard output and
1305     standard error channels.
1306 
1307     \sa setProcessChannelMode(), ProcessChannelMode, setReadChannel()
1308 */
processChannelMode() const1309 QProcess::ProcessChannelMode QProcess::processChannelMode() const
1310 {
1311     Q_D(const QProcess);
1312     return d->processChannelMode;
1313 }
1314 
1315 /*!
1316     \since 4.2
1317 
1318     Sets the channel mode of the QProcess standard output and standard
1319     error channels to the \a mode specified.
1320     This mode will be used the next time start() is called. For example:
1321 
1322     \snippet code/src_corelib_io_qprocess.cpp 0
1323 
1324     \sa processChannelMode(), ProcessChannelMode, setReadChannel()
1325 */
setProcessChannelMode(ProcessChannelMode mode)1326 void QProcess::setProcessChannelMode(ProcessChannelMode mode)
1327 {
1328     Q_D(QProcess);
1329     d->processChannelMode = mode;
1330 }
1331 
1332 /*!
1333     \since 5.2
1334 
1335     Returns the channel mode of the QProcess standard input channel.
1336 
1337     \sa setInputChannelMode(), InputChannelMode
1338 */
inputChannelMode() const1339 QProcess::InputChannelMode QProcess::inputChannelMode() const
1340 {
1341     Q_D(const QProcess);
1342     return d->inputChannelMode;
1343 }
1344 
1345 /*!
1346     \since 5.2
1347 
1348     Sets the channel mode of the QProcess standard input
1349     channel to the \a mode specified.
1350     This mode will be used the next time start() is called.
1351 
1352     \sa inputChannelMode(), InputChannelMode
1353 */
setInputChannelMode(InputChannelMode mode)1354 void QProcess::setInputChannelMode(InputChannelMode mode)
1355 {
1356     Q_D(QProcess);
1357     d->inputChannelMode = mode;
1358 }
1359 
1360 /*!
1361     Returns the current read channel of the QProcess.
1362 
1363     \sa setReadChannel()
1364 */
readChannel() const1365 QProcess::ProcessChannel QProcess::readChannel() const
1366 {
1367     Q_D(const QProcess);
1368     return ProcessChannel(d->currentReadChannel);
1369 }
1370 
1371 /*!
1372     Sets the current read channel of the QProcess to the given \a
1373     channel. The current input channel is used by the functions
1374     read(), readAll(), readLine(), and getChar(). It also determines
1375     which channel triggers QProcess to emit readyRead().
1376 
1377     \sa readChannel()
1378 */
setReadChannel(ProcessChannel channel)1379 void QProcess::setReadChannel(ProcessChannel channel)
1380 {
1381     QIODevice::setCurrentReadChannel(int(channel));
1382 }
1383 
1384 /*!
1385     Closes the read channel \a channel. After calling this function,
1386     QProcess will no longer receive data on the channel. Any data that
1387     has already been received is still available for reading.
1388 
1389     Call this function to save memory, if you are not interested in
1390     the output of the process.
1391 
1392     \sa closeWriteChannel(), setReadChannel()
1393 */
closeReadChannel(ProcessChannel channel)1394 void QProcess::closeReadChannel(ProcessChannel channel)
1395 {
1396     Q_D(QProcess);
1397 
1398     if (channel == StandardOutput)
1399         d->stdoutChannel.closed = true;
1400     else
1401         d->stderrChannel.closed = true;
1402 }
1403 
1404 /*!
1405     Schedules the write channel of QProcess to be closed. The channel
1406     will close once all data has been written to the process. After
1407     calling this function, any attempts to write to the process will
1408     fail.
1409 
1410     Closing the write channel is necessary for programs that read
1411     input data until the channel has been closed. For example, the
1412     program "more" is used to display text data in a console on both
1413     Unix and Windows. But it will not display the text data until
1414     QProcess's write channel has been closed. Example:
1415 
1416     \snippet code/src_corelib_io_qprocess.cpp 1
1417 
1418     The write channel is implicitly opened when start() is called.
1419 
1420     \sa closeReadChannel()
1421 */
closeWriteChannel()1422 void QProcess::closeWriteChannel()
1423 {
1424     Q_D(QProcess);
1425     d->stdinChannel.closed = true; // closing
1426     if (d->writeBuffer.isEmpty())
1427         d->closeWriteChannel();
1428 }
1429 
1430 /*!
1431     \since 4.2
1432 
1433     Redirects the process' standard input to the file indicated by \a
1434     fileName. When an input redirection is in place, the QProcess
1435     object will be in read-only mode (calling write() will result in
1436     error).
1437 
1438     To make the process read EOF right away, pass nullDevice() here.
1439     This is cleaner than using closeWriteChannel() before writing any
1440     data, because it can be set up prior to starting the process.
1441 
1442     If the file \a fileName does not exist at the moment start() is
1443     called or is not readable, starting the process will fail.
1444 
1445     Calling setStandardInputFile() after the process has started has no
1446     effect.
1447 
1448     \sa setStandardOutputFile(), setStandardErrorFile(),
1449         setStandardOutputProcess()
1450 */
setStandardInputFile(const QString & fileName)1451 void QProcess::setStandardInputFile(const QString &fileName)
1452 {
1453     Q_D(QProcess);
1454     d->stdinChannel = fileName;
1455 }
1456 
1457 /*!
1458     \since 4.2
1459 
1460     Redirects the process' standard output to the file \a
1461     fileName. When the redirection is in place, the standard output
1462     read channel is closed: reading from it using read() will always
1463     fail, as will readAllStandardOutput().
1464 
1465     To discard all standard output from the process, pass nullDevice()
1466     here. This is more efficient than simply never reading the standard
1467     output, as no QProcess buffers are filled.
1468 
1469     If the file \a fileName doesn't exist at the moment start() is
1470     called, it will be created. If it cannot be created, the starting
1471     will fail.
1472 
1473     If the file exists and \a mode is QIODevice::Truncate, the file
1474     will be truncated. Otherwise (if \a mode is QIODevice::Append),
1475     the file will be appended to.
1476 
1477     Calling setStandardOutputFile() after the process has started has
1478     no effect.
1479 
1480     \sa setStandardInputFile(), setStandardErrorFile(),
1481         setStandardOutputProcess()
1482 */
setStandardOutputFile(const QString & fileName,OpenMode mode)1483 void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode)
1484 {
1485     Q_ASSERT(mode == Append || mode == Truncate);
1486     Q_D(QProcess);
1487 
1488     d->stdoutChannel = fileName;
1489     d->stdoutChannel.append = mode == Append;
1490 }
1491 
1492 /*!
1493     \since 4.2
1494 
1495     Redirects the process' standard error to the file \a
1496     fileName. When the redirection is in place, the standard error
1497     read channel is closed: reading from it using read() will always
1498     fail, as will readAllStandardError(). The file will be appended to
1499     if \a mode is Append, otherwise, it will be truncated.
1500 
1501     See setStandardOutputFile() for more information on how the file
1502     is opened.
1503 
1504     Note: if setProcessChannelMode() was called with an argument of
1505     QProcess::MergedChannels, this function has no effect.
1506 
1507     \sa setStandardInputFile(), setStandardOutputFile(),
1508         setStandardOutputProcess()
1509 */
setStandardErrorFile(const QString & fileName,OpenMode mode)1510 void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode)
1511 {
1512     Q_ASSERT(mode == Append || mode == Truncate);
1513     Q_D(QProcess);
1514 
1515     d->stderrChannel = fileName;
1516     d->stderrChannel.append = mode == Append;
1517 }
1518 
1519 /*!
1520     \since 4.2
1521 
1522     Pipes the standard output stream of this process to the \a
1523     destination process' standard input.
1524 
1525     The following shell command:
1526     \snippet code/src_corelib_io_qprocess.cpp 2
1527 
1528     Can be accomplished with QProcess with the following code:
1529     \snippet code/src_corelib_io_qprocess.cpp 3
1530 */
setStandardOutputProcess(QProcess * destination)1531 void QProcess::setStandardOutputProcess(QProcess *destination)
1532 {
1533     QProcessPrivate *dfrom = d_func();
1534     QProcessPrivate *dto = destination->d_func();
1535     dfrom->stdoutChannel.pipeTo(dto);
1536     dto->stdinChannel.pipeFrom(dfrom);
1537 }
1538 
1539 #if defined(Q_OS_WIN) || defined(Q_CLANG_QDOC)
1540 
1541 /*!
1542     \since 4.7
1543 
1544     Returns the additional native command line arguments for the program.
1545 
1546     \note This function is available only on the Windows platform.
1547 
1548     \sa setNativeArguments()
1549 */
nativeArguments() const1550 QString QProcess::nativeArguments() const
1551 {
1552     Q_D(const QProcess);
1553     return d->nativeArguments;
1554 }
1555 
1556 /*!
1557     \since 4.7
1558     \overload
1559 
1560     Sets additional native command line \a arguments for the program.
1561 
1562     On operating systems where the system API for passing command line
1563     \a arguments to a subprocess natively uses a single string, one can
1564     conceive command lines which cannot be passed via QProcess's portable
1565     list-based API. In such cases this function must be used to set a
1566     string which is \e appended to the string composed from the usual
1567     argument list, with a delimiting space.
1568 
1569     \note This function is available only on the Windows platform.
1570 
1571     \sa nativeArguments()
1572 */
setNativeArguments(const QString & arguments)1573 void QProcess::setNativeArguments(const QString &arguments)
1574 {
1575     Q_D(QProcess);
1576     d->nativeArguments = arguments;
1577 }
1578 
1579 /*!
1580     \since 5.7
1581 
1582     Returns a previously set \c CreateProcess modifier function.
1583 
1584     \note This function is available only on the Windows platform.
1585 
1586     \sa setCreateProcessArgumentsModifier()
1587     \sa QProcess::CreateProcessArgumentModifier
1588 */
createProcessArgumentsModifier() const1589 QProcess::CreateProcessArgumentModifier QProcess::createProcessArgumentsModifier() const
1590 {
1591     Q_D(const QProcess);
1592     return d->modifyCreateProcessArgs;
1593 }
1594 
1595 /*!
1596     \since 5.7
1597 
1598     Sets the \a modifier for the \c CreateProcess Win32 API call.
1599     Pass \c QProcess::CreateProcessArgumentModifier() to remove a previously set one.
1600 
1601     \note This function is available only on the Windows platform and requires
1602     C++11.
1603 
1604     \sa QProcess::CreateProcessArgumentModifier
1605 */
setCreateProcessArgumentsModifier(CreateProcessArgumentModifier modifier)1606 void QProcess::setCreateProcessArgumentsModifier(CreateProcessArgumentModifier modifier)
1607 {
1608     Q_D(QProcess);
1609     d->modifyCreateProcessArgs = modifier;
1610 }
1611 
1612 #endif
1613 
1614 /*!
1615     If QProcess has been assigned a working directory, this function returns
1616     the working directory that the QProcess will enter before the program has
1617     started. Otherwise, (i.e., no directory has been assigned,) an empty
1618     string is returned, and QProcess will use the application's current
1619     working directory instead.
1620 
1621     \sa setWorkingDirectory()
1622 */
workingDirectory() const1623 QString QProcess::workingDirectory() const
1624 {
1625     Q_D(const QProcess);
1626     return d->workingDirectory;
1627 }
1628 
1629 /*!
1630     Sets the working directory to \a dir. QProcess will start the
1631     process in this directory. The default behavior is to start the
1632     process in the working directory of the calling process.
1633 
1634     \note On QNX, this may cause all application threads to
1635     temporarily freeze.
1636 
1637     \sa workingDirectory(), start()
1638 */
setWorkingDirectory(const QString & dir)1639 void QProcess::setWorkingDirectory(const QString &dir)
1640 {
1641     Q_D(QProcess);
1642     d->workingDirectory = dir;
1643 }
1644 
1645 #if QT_DEPRECATED_SINCE(5, 15)
1646 /*!
1647     \deprecated
1648     Use processId() instead.
1649 
1650     Returns the native process identifier for the running process, if
1651     available.  If no process is currently running, \c 0 is returned.
1652 
1653     \note Unlike \l processId(), pid() returns an integer on Unix and a pointer on Windows.
1654 
1655     \sa Q_PID, processId()
1656 */
pid() const1657 Q_PID QProcess::pid() const // ### Qt 6 remove or rename this method to processInformation()
1658 {
1659     Q_D(const QProcess);
1660     return d->pid;
1661 }
1662 #endif
1663 
1664 /*!
1665     \since 5.3
1666 
1667     Returns the native process identifier for the running process, if
1668     available. If no process is currently running, \c 0 is returned.
1669  */
processId() const1670 qint64 QProcess::processId() const
1671 {
1672     Q_D(const QProcess);
1673 #ifdef Q_OS_WIN
1674     return d->pid ? d->pid->dwProcessId : 0;
1675 #else
1676     return d->pid;
1677 #endif
1678 }
1679 
1680 /*! \reimp
1681 
1682     This function operates on the current read channel.
1683 
1684     \sa readChannel(), setReadChannel()
1685 */
canReadLine() const1686 bool QProcess::canReadLine() const
1687 {
1688     return QIODevice::canReadLine();
1689 }
1690 
1691 /*!
1692     Closes all communication with the process and kills it. After calling this
1693     function, QProcess will no longer emit readyRead(), and data can no
1694     longer be read or written.
1695 */
close()1696 void QProcess::close()
1697 {
1698     Q_D(QProcess);
1699     emit aboutToClose();
1700     while (waitForBytesWritten(-1))
1701         ;
1702     kill();
1703     waitForFinished(-1);
1704     d->setWriteChannelCount(0);
1705     QIODevice::close();
1706 }
1707 
1708 /*! \reimp
1709 
1710    Returns \c true if the process is not running, and no more data is available
1711    for reading; otherwise returns \c false.
1712 */
atEnd() const1713 bool QProcess::atEnd() const
1714 {
1715     return QIODevice::atEnd();
1716 }
1717 
1718 /*! \reimp
1719 */
isSequential() const1720 bool QProcess::isSequential() const
1721 {
1722     return true;
1723 }
1724 
1725 /*! \reimp
1726 */
bytesAvailable() const1727 qint64 QProcess::bytesAvailable() const
1728 {
1729     return QIODevice::bytesAvailable();
1730 }
1731 
1732 /*! \reimp
1733 */
bytesToWrite() const1734 qint64 QProcess::bytesToWrite() const
1735 {
1736     qint64 size = QIODevice::bytesToWrite();
1737 #ifdef Q_OS_WIN
1738     size += d_func()->pipeWriterBytesToWrite();
1739 #endif
1740     return size;
1741 }
1742 
1743 /*!
1744     Returns the type of error that occurred last.
1745 
1746     \sa state()
1747 */
error() const1748 QProcess::ProcessError QProcess::error() const
1749 {
1750     Q_D(const QProcess);
1751     return d->processError;
1752 }
1753 
1754 /*!
1755     Returns the current state of the process.
1756 
1757     \sa stateChanged(), error()
1758 */
state() const1759 QProcess::ProcessState QProcess::state() const
1760 {
1761     Q_D(const QProcess);
1762     return d->processState;
1763 }
1764 
1765 /*!
1766     \deprecated
1767     Sets the environment that QProcess will pass to the child process.
1768     The parameter \a environment is a list of key=value pairs.
1769 
1770     For example, the following code adds the environment variable \c{TMPDIR}:
1771 
1772     \snippet qprocess-environment/main.cpp 0
1773 
1774     \note This function is less efficient than the setProcessEnvironment()
1775     function.
1776 
1777     \sa environment(), setProcessEnvironment(), systemEnvironment()
1778 */
setEnvironment(const QStringList & environment)1779 void QProcess::setEnvironment(const QStringList &environment)
1780 {
1781     setProcessEnvironment(QProcessEnvironmentPrivate::fromList(environment));
1782 }
1783 
1784 /*!
1785     \deprecated
1786     Returns the environment that QProcess will pass to its child
1787     process, or an empty QStringList if no environment has been set
1788     using setEnvironment(). If no environment has been set, the
1789     environment of the calling process will be used.
1790 
1791     \sa processEnvironment(), setEnvironment(), systemEnvironment()
1792 */
environment() const1793 QStringList QProcess::environment() const
1794 {
1795     Q_D(const QProcess);
1796     return d->environment.toStringList();
1797 }
1798 
1799 /*!
1800     \since 4.6
1801     Sets the \a environment that QProcess will pass to the child process.
1802 
1803     For example, the following code adds the environment variable \c{TMPDIR}:
1804 
1805     \snippet qprocess-environment/main.cpp 1
1806 
1807     Note how, on Windows, environment variable names are case-insensitive.
1808 
1809     \sa processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
1810 */
setProcessEnvironment(const QProcessEnvironment & environment)1811 void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)
1812 {
1813     Q_D(QProcess);
1814     d->environment = environment;
1815 }
1816 
1817 /*!
1818     \since 4.6
1819     Returns the environment that QProcess will pass to its child
1820     process, or an empty object if no environment has been set using
1821     setEnvironment() or setProcessEnvironment(). If no environment has
1822     been set, the environment of the calling process will be used.
1823 
1824     \sa setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
1825 */
processEnvironment() const1826 QProcessEnvironment QProcess::processEnvironment() const
1827 {
1828     Q_D(const QProcess);
1829     return d->environment;
1830 }
1831 
1832 /*!
1833     Blocks until the process has started and the started() signal has
1834     been emitted, or until \a msecs milliseconds have passed.
1835 
1836     Returns \c true if the process was started successfully; otherwise
1837     returns \c false (if the operation timed out or if an error
1838     occurred).
1839 
1840     This function can operate without an event loop. It is
1841     useful when writing non-GUI applications and when performing
1842     I/O operations in a non-GUI thread.
1843 
1844     \warning Calling this function from the main (GUI) thread
1845     might cause your user interface to freeze.
1846 
1847     If msecs is -1, this function will not time out.
1848 
1849     \note On some UNIX operating systems, this function may return true but
1850     the process may later report a QProcess::FailedToStart error.
1851 
1852     \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
1853 */
waitForStarted(int msecs)1854 bool QProcess::waitForStarted(int msecs)
1855 {
1856     Q_D(QProcess);
1857     if (d->processState == QProcess::Starting)
1858         return d->waitForStarted(msecs);
1859 
1860     return d->processState == QProcess::Running;
1861 }
1862 
1863 /*! \reimp
1864 */
waitForReadyRead(int msecs)1865 bool QProcess::waitForReadyRead(int msecs)
1866 {
1867     Q_D(QProcess);
1868 
1869     if (d->processState == QProcess::NotRunning)
1870         return false;
1871     if (d->currentReadChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1872         return false;
1873     if (d->currentReadChannel == QProcess::StandardError && d->stderrChannel.closed)
1874         return false;
1875     return d->waitForReadyRead(msecs);
1876 }
1877 
1878 /*! \reimp
1879 */
waitForBytesWritten(int msecs)1880 bool QProcess::waitForBytesWritten(int msecs)
1881 {
1882     Q_D(QProcess);
1883     if (d->processState == QProcess::NotRunning)
1884         return false;
1885     if (d->processState == QProcess::Starting) {
1886         QElapsedTimer stopWatch;
1887         stopWatch.start();
1888         bool started = waitForStarted(msecs);
1889         if (!started)
1890             return false;
1891         msecs = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
1892     }
1893 
1894     return d->waitForBytesWritten(msecs);
1895 }
1896 
1897 /*!
1898     Blocks until the process has finished and the finished() signal
1899     has been emitted, or until \a msecs milliseconds have passed.
1900 
1901     Returns \c true if the process finished; otherwise returns \c false (if
1902     the operation timed out, if an error occurred, or if this QProcess
1903     is already finished).
1904 
1905     This function can operate without an event loop. It is
1906     useful when writing non-GUI applications and when performing
1907     I/O operations in a non-GUI thread.
1908 
1909     \warning Calling this function from the main (GUI) thread
1910     might cause your user interface to freeze.
1911 
1912     If msecs is -1, this function will not time out.
1913 
1914     \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
1915 */
waitForFinished(int msecs)1916 bool QProcess::waitForFinished(int msecs)
1917 {
1918     Q_D(QProcess);
1919     if (d->processState == QProcess::NotRunning)
1920         return false;
1921     if (d->processState == QProcess::Starting) {
1922         QElapsedTimer stopWatch;
1923         stopWatch.start();
1924         bool started = waitForStarted(msecs);
1925         if (!started)
1926             return false;
1927         msecs = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
1928     }
1929 
1930     return d->waitForFinished(msecs);
1931 }
1932 
1933 /*!
1934     Sets the current state of the QProcess to the \a state specified.
1935 
1936     \sa state()
1937 */
setProcessState(ProcessState state)1938 void QProcess::setProcessState(ProcessState state)
1939 {
1940     Q_D(QProcess);
1941     if (d->processState == state)
1942         return;
1943     d->processState = state;
1944     emit stateChanged(state, QPrivateSignal());
1945 }
1946 
1947 /*!
1948   This function is called in the child process context just before the
1949     program is executed on Unix or \macos (i.e., after \c fork(), but before
1950     \c execve()). Reimplement this function to do last minute initialization
1951     of the child process. Example:
1952 
1953     \snippet code/src_corelib_io_qprocess.cpp 4
1954 
1955     You cannot exit the process (by calling exit(), for instance) from
1956     this function. If you need to stop the program before it starts
1957     execution, your workaround is to emit finished() and then call
1958     exit().
1959 
1960     \warning This function is called by QProcess on Unix and \macos
1961     only. On Windows and QNX, it is not called.
1962 */
setupChildProcess()1963 void QProcess::setupChildProcess()
1964 {
1965 }
1966 
1967 /*! \reimp
1968 */
readData(char * data,qint64 maxlen)1969 qint64 QProcess::readData(char *data, qint64 maxlen)
1970 {
1971     Q_D(QProcess);
1972     Q_UNUSED(data);
1973     if (!maxlen)
1974         return 0;
1975     if (d->processState == QProcess::NotRunning)
1976         return -1;              // EOF
1977     return 0;
1978 }
1979 
1980 /*! \reimp
1981 */
writeData(const char * data,qint64 len)1982 qint64 QProcess::writeData(const char *data, qint64 len)
1983 {
1984     Q_D(QProcess);
1985 
1986     if (d->stdinChannel.closed) {
1987 #if defined QPROCESS_DEBUG
1988     qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1989            data, qt_prettyDebug(data, len, 16).constData(), len);
1990 #endif
1991         return 0;
1992     }
1993 
1994 #if defined(Q_OS_WIN)
1995     if (!d->stdinWriteTrigger) {
1996         d->stdinWriteTrigger = new QTimer;
1997         d->stdinWriteTrigger->setSingleShot(true);
1998         QObjectPrivate::connect(d->stdinWriteTrigger, &QTimer::timeout,
1999                                 d, &QProcessPrivate::_q_canWrite);
2000     }
2001 #endif
2002 
2003     d->writeBuffer.append(data, len);
2004 #ifdef Q_OS_WIN
2005     if (!d->stdinWriteTrigger->isActive())
2006         d->stdinWriteTrigger->start();
2007 #else
2008     if (d->stdinChannel.notifier)
2009         d->stdinChannel.notifier->setEnabled(true);
2010 #endif
2011 #if defined QPROCESS_DEBUG
2012     qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
2013            data, qt_prettyDebug(data, len, 16).constData(), len, len);
2014 #endif
2015     return len;
2016 }
2017 
2018 /*!
2019     Regardless of the current read channel, this function returns all
2020     data available from the standard output of the process as a
2021     QByteArray.
2022 
2023     \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
2024 */
readAllStandardOutput()2025 QByteArray QProcess::readAllStandardOutput()
2026 {
2027     ProcessChannel tmp = readChannel();
2028     setReadChannel(StandardOutput);
2029     QByteArray data = readAll();
2030     setReadChannel(tmp);
2031     return data;
2032 }
2033 
2034 /*!
2035     Regardless of the current read channel, this function returns all
2036     data available from the standard error of the process as a
2037     QByteArray.
2038 
2039     \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
2040 */
readAllStandardError()2041 QByteArray QProcess::readAllStandardError()
2042 {
2043     ProcessChannel tmp = readChannel();
2044     setReadChannel(StandardError);
2045     QByteArray data = readAll();
2046     setReadChannel(tmp);
2047     return data;
2048 }
2049 
2050 /*!
2051     Starts the given \a program in a new process, passing the command line
2052     arguments in \a arguments.
2053 
2054     The QProcess object will immediately enter the Starting state. If the
2055     process starts successfully, QProcess will emit started(); otherwise,
2056     errorOccurred() will be emitted.
2057 
2058     \note Processes are started asynchronously, which means the started()
2059     and errorOccurred() signals may be delayed. Call waitForStarted() to make
2060     sure the process has started (or has failed to start) and those signals
2061     have been emitted.
2062 
2063     \note No further splitting of the arguments is performed.
2064 
2065     \b{Windows:} The arguments are quoted and joined into a command line
2066     that is compatible with the \c CommandLineToArgvW() Windows function.
2067     For programs that have different command line quoting requirements,
2068     you need to use setNativeArguments(). One notable program that does
2069     not follow the \c CommandLineToArgvW() rules is cmd.exe and, by
2070     consequence, all batch scripts.
2071 
2072     The OpenMode is set to \a mode.
2073 
2074     If the QProcess object is already running a process, a warning may be
2075     printed at the console, and the existing process will continue running
2076     unaffected.
2077 
2078     \sa processId(), started(), waitForStarted(), setNativeArguments()
2079 */
start(const QString & program,const QStringList & arguments,OpenMode mode)2080 void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
2081 {
2082     Q_D(QProcess);
2083     if (d->processState != NotRunning) {
2084         qWarning("QProcess::start: Process is already running");
2085         return;
2086     }
2087     if (program.isEmpty()) {
2088         d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2089         return;
2090     }
2091 
2092     d->program = program;
2093     d->arguments = arguments;
2094 
2095     d->start(mode);
2096 }
2097 
2098 /*!
2099     \since 5.1
2100     \overload
2101 
2102     Starts the program set by setProgram() with arguments set by setArguments().
2103     The OpenMode is set to \a mode.
2104 
2105     \sa open(), setProgram(), setArguments()
2106  */
start(OpenMode mode)2107 void QProcess::start(OpenMode mode)
2108 {
2109     Q_D(QProcess);
2110     if (d->processState != NotRunning) {
2111         qWarning("QProcess::start: Process is already running");
2112         return;
2113     }
2114     if (d->program.isEmpty()) {
2115         d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2116         return;
2117     }
2118 
2119     d->start(mode);
2120 }
2121 
2122 /*!
2123     \since 5.10
2124 
2125     Starts the program set by setProgram() with arguments set by setArguments()
2126     in a new process, and detaches from it. Returns \c true on success;
2127     otherwise returns \c false. If the calling process exits, the
2128     detached process will continue to run unaffected.
2129 
2130     \b{Unix:} The started process will run in its own session and act
2131     like a daemon.
2132 
2133     The process will be started in the directory set by setWorkingDirectory().
2134     If workingDirectory() is empty, the working directory is inherited
2135     from the calling process.
2136 
2137     \note On QNX, this may cause all application threads to
2138     temporarily freeze.
2139 
2140     If the function is successful then *\a pid is set to the process identifier
2141     of the started process. Note that the child process may exit and the PID
2142     may become invalid without notice. Furthermore, after the child process
2143     exits, the same PID may be recycled and used by a completely different
2144     process. User code should be careful when using this variable, especially
2145     if one intends to forcibly terminate the process by operating system means.
2146 
2147     Only the following property setters are supported by startDetached():
2148     \list
2149     \li setArguments()
2150     \li setCreateProcessArgumentsModifier()
2151     \li setNativeArguments()
2152     \li setProcessEnvironment()
2153     \li setProgram()
2154     \li setStandardErrorFile()
2155     \li setStandardInputFile()
2156     \li setStandardOutputFile()
2157     \li setWorkingDirectory()
2158     \endlist
2159     All other properties of the QProcess object are ignored.
2160 
2161     \note The called process inherits the console window of the calling
2162     process. To suppress console output, redirect standard/error output to
2163     QProcess::nullDevice().
2164 
2165     \sa start()
2166     \sa startDetached(const QString &program, const QStringList &arguments,
2167                       const QString &workingDirectory, qint64 *pid)
2168     \sa startDetached(const QString &command)
2169 */
startDetached(qint64 * pid)2170 bool QProcess::startDetached(qint64 *pid)
2171 {
2172     Q_D(QProcess);
2173     if (d->processState != NotRunning) {
2174         qWarning("QProcess::startDetached: Process is already running");
2175         return false;
2176     }
2177     if (d->program.isEmpty()) {
2178         d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2179         return false;
2180     }
2181     return d->startDetached(pid);
2182 }
2183 
2184 /*!
2185     Starts the program set by setProgram() with arguments set by setArguments().
2186     The OpenMode is set to \a mode.
2187 
2188     This method is an alias for start(), and exists only to fully implement
2189     the interface defined by QIODevice.
2190 
2191     Returns \c true if the program has been started.
2192 
2193     \sa start(), setProgram(), setArguments()
2194 */
open(OpenMode mode)2195 bool QProcess::open(OpenMode mode)
2196 {
2197     Q_D(QProcess);
2198     if (d->processState != NotRunning) {
2199         qWarning("QProcess::start: Process is already running");
2200         return false;
2201     }
2202     if (d->program.isEmpty()) {
2203         qWarning("QProcess::start: program not set");
2204         return false;
2205     }
2206 
2207     d->start(mode);
2208     return true;
2209 }
2210 
start(QIODevice::OpenMode mode)2211 void QProcessPrivate::start(QIODevice::OpenMode mode)
2212 {
2213     Q_Q(QProcess);
2214 #if defined QPROCESS_DEBUG
2215     qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
2216 #endif
2217 
2218     if (stdinChannel.type != QProcessPrivate::Channel::Normal)
2219         mode &= ~QIODevice::WriteOnly;     // not open for writing
2220     if (stdoutChannel.type != QProcessPrivate::Channel::Normal &&
2221         (stderrChannel.type != QProcessPrivate::Channel::Normal ||
2222          processChannelMode == QProcess::MergedChannels))
2223         mode &= ~QIODevice::ReadOnly;      // not open for reading
2224     if (mode == 0)
2225         mode = QIODevice::Unbuffered;
2226     if ((mode & QIODevice::ReadOnly) == 0) {
2227         if (stdoutChannel.type == QProcessPrivate::Channel::Normal)
2228             q->setStandardOutputFile(q->nullDevice());
2229         if (stderrChannel.type == QProcessPrivate::Channel::Normal
2230             && processChannelMode != QProcess::MergedChannels)
2231             q->setStandardErrorFile(q->nullDevice());
2232     }
2233 
2234     q->QIODevice::open(mode);
2235 
2236     if (q->isReadable() && processChannelMode != QProcess::MergedChannels)
2237         setReadChannelCount(2);
2238 
2239     stdinChannel.closed = false;
2240     stdoutChannel.closed = false;
2241     stderrChannel.closed = false;
2242 
2243     exitCode = 0;
2244     exitStatus = QProcess::NormalExit;
2245     processError = QProcess::UnknownError;
2246     errorString.clear();
2247     startProcess();
2248 }
2249 
2250 /*!
2251     \since 5.15
2252 
2253     Splits the string \a command into a list of tokens, and returns
2254     the list.
2255 
2256     Tokens with spaces can be surrounded by double quotes; three
2257     consecutive double quotes represent the quote character itself.
2258 */
splitCommand(QStringView command)2259 QStringList QProcess::splitCommand(QStringView command)
2260 {
2261     QStringList args;
2262     QString tmp;
2263     int quoteCount = 0;
2264     bool inQuote = false;
2265 
2266     // handle quoting. tokens can be surrounded by double quotes
2267     // "hello world". three consecutive double quotes represent
2268     // the quote character itself.
2269     for (int i = 0; i < command.size(); ++i) {
2270         if (command.at(i) == QLatin1Char('"')) {
2271             ++quoteCount;
2272             if (quoteCount == 3) {
2273                 // third consecutive quote
2274                 quoteCount = 0;
2275                 tmp += command.at(i);
2276             }
2277             continue;
2278         }
2279         if (quoteCount) {
2280             if (quoteCount == 1)
2281                 inQuote = !inQuote;
2282             quoteCount = 0;
2283         }
2284         if (!inQuote && command.at(i).isSpace()) {
2285             if (!tmp.isEmpty()) {
2286                 args += tmp;
2287                 tmp.clear();
2288             }
2289         } else {
2290             tmp += command.at(i);
2291         }
2292     }
2293     if (!tmp.isEmpty())
2294         args += tmp;
2295 
2296     return args;
2297 }
2298 
2299 /*!
2300     \obsolete
2301     \overload
2302 
2303     Starts the command \a command in a new process.
2304     The OpenMode is set to \a mode.
2305 
2306     \a command is a single string of text containing both the program name
2307     and its arguments. The arguments are separated by one or more spaces.
2308     For example:
2309 
2310     \snippet code/src_corelib_io_qprocess.cpp 5
2311 
2312     Arguments containing spaces must be quoted to be correctly supplied to
2313     the new process. For example:
2314 
2315     \snippet code/src_corelib_io_qprocess.cpp 6
2316 
2317     Literal quotes in the \a command string are represented by triple quotes.
2318     For example:
2319 
2320     \snippet code/src_corelib_io_qprocess.cpp 7
2321 
2322     After the \a command string has been split and unquoted, this function
2323     behaves like the overload which takes the arguments as a string list.
2324 
2325     You can disable this overload by defining \c
2326     QT_NO_PROCESS_COMBINED_ARGUMENT_START when you compile your applications.
2327     This can be useful if you want to ensure that you are not splitting arguments
2328     unintentionally, for example. In virtually all cases, using the other overload
2329     is the preferred method.
2330 
2331     On operating systems where the system API for passing command line
2332     arguments to a subprocess natively uses a single string (Windows), one can
2333     conceive command lines which cannot be passed via QProcess's portable
2334     list-based API. In these rare cases you need to use setProgram() and
2335     setNativeArguments() instead of this function.
2336 
2337     \sa splitCommand()
2338 
2339 */
2340 #if !defined(QT_NO_PROCESS_COMBINED_ARGUMENT_START)
start(const QString & command,OpenMode mode)2341 void QProcess::start(const QString &command, OpenMode mode)
2342 {
2343     QStringList args = splitCommand(command);
2344     if (args.isEmpty()) {
2345         Q_D(QProcess);
2346         d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2347         return;
2348     }
2349 
2350     const QString prog = args.takeFirst();
2351 
2352     start(prog, args, mode);
2353 }
2354 #endif
2355 
2356 /*!
2357     \since 5.0
2358 
2359     Returns the program the process was last started with.
2360 
2361     \sa start()
2362 */
program() const2363 QString QProcess::program() const
2364 {
2365     Q_D(const QProcess);
2366     return d->program;
2367 }
2368 
2369 /*!
2370     \since 5.1
2371 
2372     Set the \a program to use when starting the process.
2373     This function must be called before start().
2374 
2375     \sa start(), setArguments(), program()
2376 */
setProgram(const QString & program)2377 void QProcess::setProgram(const QString &program)
2378 {
2379     Q_D(QProcess);
2380     if (d->processState != NotRunning) {
2381         qWarning("QProcess::setProgram: Process is already running");
2382         return;
2383     }
2384     d->program = program;
2385 }
2386 
2387 /*!
2388     \since 5.0
2389 
2390     Returns the command line arguments the process was last started with.
2391 
2392     \sa start()
2393 */
arguments() const2394 QStringList QProcess::arguments() const
2395 {
2396     Q_D(const QProcess);
2397     return d->arguments;
2398 }
2399 
2400 /*!
2401     \since 5.1
2402 
2403     Set the \a arguments to pass to the called program when starting the process.
2404     This function must be called before start().
2405 
2406     \sa start(), setProgram(), arguments()
2407 */
setArguments(const QStringList & arguments)2408 void QProcess::setArguments(const QStringList &arguments)
2409 {
2410     Q_D(QProcess);
2411     if (d->processState != NotRunning) {
2412         qWarning("QProcess::setProgram: Process is already running");
2413         return;
2414     }
2415     d->arguments = arguments;
2416 }
2417 
2418 /*!
2419     Attempts to terminate the process.
2420 
2421     The process may not exit as a result of calling this function (it is given
2422     the chance to prompt the user for any unsaved files, etc).
2423 
2424     On Windows, terminate() posts a WM_CLOSE message to all top-level windows
2425     of the process and then to the main thread of the process itself. On Unix
2426     and \macos the \c SIGTERM signal is sent.
2427 
2428     Console applications on Windows that do not run an event loop, or whose
2429     event loop does not handle the WM_CLOSE message, can only be terminated by
2430     calling kill().
2431 
2432     \sa kill()
2433 */
terminate()2434 void QProcess::terminate()
2435 {
2436     Q_D(QProcess);
2437     d->terminateProcess();
2438 }
2439 
2440 /*!
2441     Kills the current process, causing it to exit immediately.
2442 
2443     On Windows, kill() uses TerminateProcess, and on Unix and \macos, the
2444     SIGKILL signal is sent to the process.
2445 
2446     \sa terminate()
2447 */
kill()2448 void QProcess::kill()
2449 {
2450     Q_D(QProcess);
2451     d->killProcess();
2452 }
2453 
2454 /*!
2455     Returns the exit code of the last process that finished.
2456 
2457     This value is not valid unless exitStatus() returns NormalExit.
2458 */
exitCode() const2459 int QProcess::exitCode() const
2460 {
2461     Q_D(const QProcess);
2462     return d->exitCode;
2463 }
2464 
2465 /*!
2466     \since 4.1
2467 
2468     Returns the exit status of the last process that finished.
2469 
2470     On Windows, if the process was terminated with TerminateProcess() from
2471     another application, this function will still return NormalExit
2472     unless the exit code is less than 0.
2473 */
exitStatus() const2474 QProcess::ExitStatus QProcess::exitStatus() const
2475 {
2476     Q_D(const QProcess);
2477     return d->exitStatus;
2478 }
2479 
2480 /*!
2481     Starts the program \a program with the arguments \a arguments in a
2482     new process, waits for it to finish, and then returns the exit
2483     code of the process. Any data the new process writes to the
2484     console is forwarded to the calling process.
2485 
2486     The environment and working directory are inherited from the calling
2487     process.
2488 
2489     Argument handling is identical to the respective start() overload.
2490 
2491     If the process cannot be started, -2 is returned. If the process
2492     crashes, -1 is returned. Otherwise, the process' exit code is
2493     returned.
2494 
2495     \sa start()
2496 */
execute(const QString & program,const QStringList & arguments)2497 int QProcess::execute(const QString &program, const QStringList &arguments)
2498 {
2499     QProcess process;
2500     process.setProcessChannelMode(ForwardedChannels);
2501     process.start(program, arguments);
2502     if (!process.waitForFinished(-1) || process.error() == FailedToStart)
2503         return -2;
2504     return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2505 }
2506 
2507 /*!
2508     \obsolete
2509     \overload
2510 
2511     Starts the program \a command in a new process, waits for it to finish,
2512     and then returns the exit code.
2513 
2514     Argument handling is identical to the respective start() overload.
2515 
2516     After the \a command string has been split and unquoted, this function
2517     behaves like the overload which takes the arguments as a string list.
2518 
2519     \sa start(), splitCommand()
2520 */
execute(const QString & command)2521 int QProcess::execute(const QString &command)
2522 {
2523     QStringList args = splitCommand(command);
2524     if (args.isEmpty())
2525         return -2;
2526     QString program = args.takeFirst();
2527     return execute(program, args);
2528 }
2529 
2530 /*!
2531     \overload startDetached()
2532 
2533     Starts the program \a program with the arguments \a arguments in a
2534     new process, and detaches from it. Returns \c true on success;
2535     otherwise returns \c false. If the calling process exits, the
2536     detached process will continue to run unaffected.
2537 
2538     Argument handling is identical to the respective start() overload.
2539 
2540     The process will be started in the directory \a workingDirectory.
2541     If \a workingDirectory is empty, the working directory is inherited
2542     from the calling process.
2543 
2544     If the function is successful then *\a pid is set to the process
2545     identifier of the started process.
2546 
2547     \sa start()
2548 */
startDetached(const QString & program,const QStringList & arguments,const QString & workingDirectory,qint64 * pid)2549 bool QProcess::startDetached(const QString &program,
2550                              const QStringList &arguments,
2551                              const QString &workingDirectory,
2552                              qint64 *pid)
2553 {
2554     QProcess process;
2555     process.setProgram(program);
2556     process.setArguments(arguments);
2557     process.setWorkingDirectory(workingDirectory);
2558     return process.startDetached(pid);
2559 }
2560 
2561 /*!
2562     \internal
2563 */
startDetached(const QString & program,const QStringList & arguments)2564 bool QProcess::startDetached(const QString &program,
2565                              const QStringList &arguments)
2566 {
2567     QProcess process;
2568     process.setProgram(program);
2569     process.setArguments(arguments);
2570     return process.startDetached();
2571 }
2572 
2573 /*!
2574     \obsolete
2575     \overload startDetached()
2576 
2577     Starts the command \a command in a new process, and detaches from it.
2578     Returns \c true on success; otherwise returns \c false.
2579 
2580     Argument handling is identical to the respective start() overload.
2581 
2582     After the \a command string has been split and unquoted, this function
2583     behaves like the overload which takes the arguments as a string list.
2584 
2585     \sa start(const QString &command, QIODevice::OpenMode mode), splitCommand()
2586 */
startDetached(const QString & command)2587 bool QProcess::startDetached(const QString &command)
2588 {
2589     QStringList args = splitCommand(command);
2590     if (args.isEmpty())
2591         return false;
2592 
2593     QProcess process;
2594     process.setProgram(args.takeFirst());
2595     process.setArguments(args);
2596     return process.startDetached();
2597 }
2598 
2599 QT_BEGIN_INCLUDE_NAMESPACE
2600 #if defined(Q_OS_MACX)
2601 # include <crt_externs.h>
2602 # define environ (*_NSGetEnviron())
2603 #elif defined(QT_PLATFORM_UIKIT)
2604   static char *qt_empty_environ[] = { 0 };
2605 #define environ qt_empty_environ
2606 #elif !defined(Q_OS_WIN)
2607   extern char **environ;
2608 #endif
2609 QT_END_INCLUDE_NAMESPACE
2610 
2611 /*!
2612     \since 4.1
2613 
2614     Returns the environment of the calling process as a list of
2615     key=value pairs. Example:
2616 
2617     \snippet code/src_corelib_io_qprocess.cpp 8
2618 
2619     This function does not cache the system environment. Therefore, it's
2620     possible to obtain an updated version of the environment if low-level C
2621     library functions like \tt setenv or \tt putenv have been called.
2622 
2623     However, note that repeated calls to this function will recreate the
2624     list of environment variables, which is a non-trivial operation.
2625 
2626     \note For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
2627 
2628     \sa QProcessEnvironment::systemEnvironment(), setProcessEnvironment()
2629 */
systemEnvironment()2630 QStringList QProcess::systemEnvironment()
2631 {
2632     QStringList tmp;
2633     char *entry = nullptr;
2634     int count = 0;
2635     while ((entry = environ[count++]))
2636         tmp << QString::fromLocal8Bit(entry);
2637     return tmp;
2638 }
2639 
2640 /*!
2641     \fn QProcessEnvironment QProcessEnvironment::systemEnvironment()
2642 
2643     \since 4.6
2644 
2645     \brief The systemEnvironment function returns the environment of
2646     the calling process.
2647 
2648     It is returned as a QProcessEnvironment. This function does not
2649     cache the system environment. Therefore, it's possible to obtain
2650     an updated version of the environment if low-level C library
2651     functions like \tt setenv or \tt putenv have been called.
2652 
2653     However, note that repeated calls to this function will recreate the
2654     QProcessEnvironment object, which is a non-trivial operation.
2655 
2656     \sa QProcess::systemEnvironment()
2657 */
2658 
2659 /*!
2660     \since 5.2
2661 
2662     \brief The null device of the operating system.
2663 
2664     The returned file path uses native directory separators.
2665 
2666     \sa QProcess::setStandardInputFile(), QProcess::setStandardOutputFile(),
2667         QProcess::setStandardErrorFile()
2668 */
nullDevice()2669 QString QProcess::nullDevice()
2670 {
2671 #ifdef Q_OS_WIN
2672     return QStringLiteral("\\\\.\\NUL");
2673 #elif defined(_PATH_DEVNULL)
2674     return QStringLiteral(_PATH_DEVNULL);
2675 #else
2676     return QStringLiteral("/dev/null");
2677 #endif
2678 }
2679 
2680 /*!
2681     \typedef Q_PID
2682     \relates QProcess
2683 
2684     Typedef for the identifiers used to represent processes on the underlying
2685     platform. On Unix, this corresponds to \l qint64; on Windows, it
2686     corresponds to \c{_PROCESS_INFORMATION*}.
2687 
2688     \sa QProcess::pid()
2689 */
2690 
2691 #endif // QT_CONFIG(process)
2692 
2693 QT_END_NAMESPACE
2694 
2695 #include "moc_qprocess.cpp"
2696