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