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 QT_HAS_INCLUDE(<paths.h>)
104#include <paths.h>
105#endif
106
107QT_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
159QStringList 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
168QProcessEnvironment 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
186QStringList 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
197void 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*/
218QProcessEnvironment::QProcessEnvironment()
219 : d(0)
220{
221}
222
223/*!
224 Frees the resources associated with this QProcessEnvironment object.
225*/
226QProcessEnvironment::~QProcessEnvironment()
227{
228}
229
230/*!
231 Creates a QProcessEnvironment object that is a copy of \a other.
232*/
233QProcessEnvironment::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*/
242QProcessEnvironment &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*/
273bool 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*/
294bool 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*/
306void 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*/
321bool 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*/
340void 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*/
355void 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*/
370QString 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*/
395QStringList 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*/
408QStringList 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*/
422void 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
433void QProcessPrivate::Channel::clear()
434{
435 switch (type) {
436 case PipeSource:
437 Q_ASSERT(process);
438 process->stdinChannel.type = Normal;
439 process->stdinChannel.process = 0;
440 break;
441 case PipeSink:
442 Q_ASSERT(process);
443 process->stdoutChannel.type = Normal;
444 process->stdoutChannel.process = 0;
445 break;
446 }
447
448 type = Normal;
449 file.clear();
450 process = 0;
451}
452
453/*!
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*/
860QProcessPrivate::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 = 0;
873 deathNotifier = 0;
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*/
890QProcessPrivate::~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*/
901void 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 = 0;
928 }
929 if (stderrChannel.notifier) {
930 delete stderrChannel.notifier;
931 stderrChannel.notifier = 0;
932 }
933 if (stdinChannel.notifier) {
934 delete stdinChannel.notifier;
935 stdinChannel.notifier = 0;
936 }
937 if (startupSocketNotifier) {
938 delete startupSocketNotifier;
939 startupSocketNotifier = 0;
940 }
941 if (deathNotifier) {
942 delete deathNotifier;
943 deathNotifier = 0;
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*/
959void 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*/
991void 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)
998QT_WARNING_PUSH
999QT_WARNING_DISABLE_DEPRECATED
1000 emit q->error(processError);
1001QT_WARNING_POP
1002#endif
1003}
1004
1005/*!
1006 \internal
1007 Returns true if we emitted readyRead().
1008*/
1009bool 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 %d bytes from the process' output",
1053 int(channel - &stdinChannel), int(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*/
1082bool QProcessPrivate::_q_canReadStandardOutput()
1083{
1084 return tryReadFromChannel(&stdoutChannel);
1085}
1086
1087/*!
1088 \internal
1089*/
1090bool QProcessPrivate::_q_canReadStandardError()
1091{
1092 return tryReadFromChannel(&stderrChannel);
1093}
1094
1095/*!
1096 \internal
1097*/
1098bool 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*/
1121bool 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)
1179QT_WARNING_PUSH
1180QT_WARNING_DISABLE_DEPRECATED
1181 emit q->finished(exitCode);
1182QT_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*/
1195bool 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*/
1225void 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 = 0;
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*/
1245QProcess::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*/
1259QProcess::~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*/
1283QProcess::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*/
1295void 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*/
1309QProcess::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*/
1326void 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*/
1339QProcess::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*/
1354void 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*/
1365QProcess::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*/
1379void 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*/
1394void 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*/
1422void 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*/
1451void 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*/
1483void 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*/
1510void 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*/
1531void 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*/
1550QString 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*/
1573void 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*/
1589QProcess::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*/
1606void 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*/
1623QString 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*/
1639void QProcess::setWorkingDirectory(const QString &dir)
1640{
1641 Q_D(QProcess);
1642 d->workingDirectory = dir;
1643}
1644
1645
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*/
1657Q_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
1663/*!
1664 \since 5.3
1665
1666 Returns the native process identifier for the running process, if
1667 available. If no process is currently running, \c 0 is returned.
1668 */
1669qint64 QProcess::processId() const
1670{
1671 Q_D(const QProcess);
1672#ifdef Q_OS_WIN
1673 return d->pid ? d->pid->dwProcessId : 0;
1674#else
1675 return d->pid;
1676#endif
1677}
1678
1679/*! \reimp
1680
1681 This function operates on the current read channel.
1682
1683 \sa readChannel(), setReadChannel()
1684*/
1685bool QProcess::canReadLine() const
1686{
1687 return QIODevice::canReadLine();
1688}
1689
1690/*!
1691 Closes all communication with the process and kills it. After calling this
1692 function, QProcess will no longer emit readyRead(), and data can no
1693 longer be read or written.
1694*/
1695void QProcess::close()
1696{
1697 Q_D(QProcess);
1698 emit aboutToClose();
1699 while (waitForBytesWritten(-1))
1700 ;
1701 kill();
1702 waitForFinished(-1);
1703 d->setWriteChannelCount(0);
1704 QIODevice::close();
1705}
1706
1707/*! \reimp
1708
1709 Returns \c true if the process is not running, and no more data is available
1710 for reading; otherwise returns \c false.
1711*/
1712bool QProcess::atEnd() const
1713{
1714 return QIODevice::atEnd();
1715}
1716
1717/*! \reimp
1718*/
1719bool QProcess::isSequential() const
1720{
1721 return true;
1722}
1723
1724/*! \reimp
1725*/
1726qint64 QProcess::bytesAvailable() const
1727{
1728 return QIODevice::bytesAvailable();
1729}
1730
1731/*! \reimp
1732*/
1733qint64 QProcess::bytesToWrite() const
1734{
1735 qint64 size = QIODevice::bytesToWrite();
1736#ifdef Q_OS_WIN
1737 size += d_func()->pipeWriterBytesToWrite();
1738#endif
1739 return size;
1740}
1741
1742/*!
1743 Returns the type of error that occurred last.
1744
1745 \sa state()
1746*/
1747QProcess::ProcessError QProcess::error() const
1748{
1749 Q_D(const QProcess);
1750 return d->processError;
1751}
1752
1753/*!
1754 Returns the current state of the process.
1755
1756 \sa stateChanged(), error()
1757*/
1758QProcess::ProcessState QProcess::state() const
1759{
1760 Q_D(const QProcess);
1761 return d->processState;
1762}
1763
1764/*!
1765 \deprecated
1766 Sets the environment that QProcess will pass to the child process.
1767 The parameter \a environment is a list of key=value pairs.
1768
1769 For example, the following code adds the environment variable \c{TMPDIR}:
1770
1771 \snippet qprocess-environment/main.cpp 0
1772
1773 \note This function is less efficient than the setProcessEnvironment()
1774 function.
1775
1776 \sa environment(), setProcessEnvironment(), systemEnvironment()
1777*/
1778void QProcess::setEnvironment(const QStringList &environment)
1779{
1780 setProcessEnvironment(QProcessEnvironmentPrivate::fromList(environment));
1781}
1782
1783/*!
1784 \deprecated
1785 Returns the environment that QProcess will pass to its child
1786 process, or an empty QStringList if no environment has been set
1787 using setEnvironment(). If no environment has been set, the
1788 environment of the calling process will be used.
1789
1790 \sa processEnvironment(), setEnvironment(), systemEnvironment()
1791*/
1792QStringList QProcess::environment() const
1793{
1794 Q_D(const QProcess);
1795 return d->environment.toStringList();
1796}
1797
1798/*!
1799 \since 4.6
1800 Sets the \a environment that QProcess will pass to the child process.
1801
1802 For example, the following code adds the environment variable \c{TMPDIR}:
1803
1804 \snippet qprocess-environment/main.cpp 1
1805
1806 Note how, on Windows, environment variable names are case-insensitive.
1807
1808 \sa processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
1809*/
1810void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)
1811{
1812 Q_D(QProcess);
1813 d->environment = environment;
1814}
1815
1816/*!
1817 \since 4.6
1818 Returns the environment that QProcess will pass to its child
1819 process, or an empty object if no environment has been set using
1820 setEnvironment() or setProcessEnvironment(). If no environment has
1821 been set, the environment of the calling process will be used.
1822
1823 \sa setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
1824*/
1825QProcessEnvironment QProcess::processEnvironment() const
1826{
1827 Q_D(const QProcess);
1828 return d->environment;
1829}
1830
1831/*!
1832 Blocks until the process has started and the started() signal has
1833 been emitted, or until \a msecs milliseconds have passed.
1834
1835 Returns \c true if the process was started successfully; otherwise
1836 returns \c false (if the operation timed out or if an error
1837 occurred).
1838
1839 This function can operate without an event loop. It is
1840 useful when writing non-GUI applications and when performing
1841 I/O operations in a non-GUI thread.
1842
1843 \warning Calling this function from the main (GUI) thread
1844 might cause your user interface to freeze.
1845
1846 If msecs is -1, this function will not time out.
1847
1848 \note On some UNIX operating systems, this function may return true but
1849 the process may later report a QProcess::FailedToStart error.
1850
1851 \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
1852*/
1853bool QProcess::waitForStarted(int msecs)
1854{
1855 Q_D(QProcess);
1856 if (d->processState == QProcess::Starting)
1857 return d->waitForStarted(msecs);
1858
1859 return d->processState == QProcess::Running;
1860}
1861
1862/*! \reimp
1863*/
1864bool QProcess::waitForReadyRead(int msecs)
1865{
1866 Q_D(QProcess);
1867
1868 if (d->processState == QProcess::NotRunning)
1869 return false;
1870 if (d->currentReadChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1871 return false;
1872 if (d->currentReadChannel == QProcess::StandardError && d->stderrChannel.closed)
1873 return false;
1874 return d->waitForReadyRead(msecs);
1875}
1876
1877/*! \reimp
1878*/
1879bool QProcess::waitForBytesWritten(int msecs)
1880{
1881 Q_D(QProcess);
1882 if (d->processState == QProcess::NotRunning)
1883 return false;
1884 if (d->processState == QProcess::Starting) {
1885 QElapsedTimer stopWatch;
1886 stopWatch.start();
1887 bool started = waitForStarted(msecs);
1888 if (!started)
1889 return false;
1890 msecs = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
1891 }
1892
1893 return d->waitForBytesWritten(msecs);
1894}
1895
1896/*!
1897 Blocks until the process has finished and the finished() signal
1898 has been emitted, or until \a msecs milliseconds have passed.
1899
1900 Returns \c true if the process finished; otherwise returns \c false (if
1901 the operation timed out, if an error occurred, or if this QProcess
1902 is already finished).
1903
1904 This function can operate without an event loop. It is
1905 useful when writing non-GUI applications and when performing
1906 I/O operations in a non-GUI thread.
1907
1908 \warning Calling this function from the main (GUI) thread
1909 might cause your user interface to freeze.
1910
1911 If msecs is -1, this function will not time out.
1912
1913 \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
1914*/
1915bool QProcess::waitForFinished(int msecs)
1916{
1917 Q_D(QProcess);
1918 if (d->processState == QProcess::NotRunning)
1919 return false;
1920 if (d->processState == QProcess::Starting) {
1921 QElapsedTimer stopWatch;
1922 stopWatch.start();
1923 bool started = waitForStarted(msecs);
1924 if (!started)
1925 return false;
1926 msecs = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
1927 }
1928
1929 return d->waitForFinished(msecs);
1930}
1931
1932/*!
1933 Sets the current state of the QProcess to the \a state specified.
1934
1935 \sa state()
1936*/
1937void QProcess::setProcessState(ProcessState state)
1938{
1939 Q_D(QProcess);
1940 if (d->processState == state)
1941 return;
1942 d->processState = state;
1943 emit stateChanged(state, QPrivateSignal());
1944}
1945
1946/*!
1947 This function is called in the child process context just before the
1948 program is executed on Unix or \macos (i.e., after \c fork(), but before
1949 \c execve()). Reimplement this function to do last minute initialization
1950 of the child process. Example:
1951
1952 \snippet code/src_corelib_io_qprocess.cpp 4
1953
1954 You cannot exit the process (by calling exit(), for instance) from
1955 this function. If you need to stop the program before it starts
1956 execution, your workaround is to emit finished() and then call
1957 exit().
1958
1959 \warning This function is called by QProcess on Unix and \macos
1960 only. On Windows and QNX, it is not called.
1961*/
1962void QProcess::setupChildProcess()
1963{
1964}
1965
1966/*! \reimp
1967*/
1968qint64 QProcess::readData(char *data, qint64 maxlen)
1969{
1970 Q_D(QProcess);
1971 Q_UNUSED(data);
1972 if (!maxlen)
1973 return 0;
1974 if (d->processState == QProcess::NotRunning)
1975 return -1; // EOF
1976 return 0;
1977}
1978
1979/*! \reimp
1980*/
1981qint64 QProcess::writeData(const char *data, qint64 len)
1982{
1983 Q_D(QProcess);
1984
1985 if (d->stdinChannel.closed) {
1986#if defined QPROCESS_DEBUG
1987 qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1988 data, qt_prettyDebug(data, len, 16).constData(), len);
1989#endif
1990 return 0;
1991 }
1992
1993#if defined(Q_OS_WIN)
1994 if (!d->stdinWriteTrigger) {
1995 d->stdinWriteTrigger = new QTimer;
1996 d->stdinWriteTrigger->setSingleShot(true);
1997 QObjectPrivate::connect(d->stdinWriteTrigger, &QTimer::timeout,
1998 d, &QProcessPrivate::_q_canWrite);
1999 }
2000#endif
2001
2002 d->writeBuffer.append(data, len);
2003#ifdef Q_OS_WIN
2004 if (!d->stdinWriteTrigger->isActive())
2005 d->stdinWriteTrigger->start();
2006#else
2007 if (d->stdinChannel.notifier)
2008 d->stdinChannel.notifier->setEnabled(true);
2009#endif
2010#if defined QPROCESS_DEBUG
2011 qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
2012 data, qt_prettyDebug(data, len, 16).constData(), len, len);
2013#endif
2014 return len;
2015}
2016
2017/*!
2018 Regardless of the current read channel, this function returns all
2019 data available from the standard output of the process as a
2020 QByteArray.
2021
2022 \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
2023*/
2024QByteArray QProcess::readAllStandardOutput()
2025{
2026 ProcessChannel tmp = readChannel();
2027 setReadChannel(StandardOutput);
2028 QByteArray data = readAll();
2029 setReadChannel(tmp);
2030 return data;
2031}
2032
2033/*!
2034 Regardless of the current read channel, this function returns all
2035 data available from the standard error of the process as a
2036 QByteArray.
2037
2038 \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
2039*/
2040QByteArray QProcess::readAllStandardError()
2041{
2042 ProcessChannel tmp = readChannel();
2043 setReadChannel(StandardError);
2044 QByteArray data = readAll();
2045 setReadChannel(tmp);
2046 return data;
2047}
2048
2049/*!
2050 Starts the given \a program in a new process, passing the command line
2051 arguments in \a arguments.
2052
2053 The QProcess object will immediately enter the Starting state. If the
2054 process starts successfully, QProcess will emit started(); otherwise,
2055 errorOccurred() will be emitted.
2056
2057 \note Processes are started asynchronously, which means the started()
2058 and errorOccurred() signals may be delayed. Call waitForStarted() to make
2059 sure the process has started (or has failed to start) and those signals
2060 have been emitted.
2061
2062 \note No further splitting of the arguments is performed.
2063
2064 \b{Windows:} The arguments are quoted and joined into a command line
2065 that is compatible with the \c CommandLineToArgvW() Windows function.
2066 For programs that have different command line quoting requirements,
2067 you need to use setNativeArguments(). One notable program that does
2068 not follow the \c CommandLineToArgvW() rules is cmd.exe and, by
2069 consequence, all batch scripts.
2070
2071 The OpenMode is set to \a mode.
2072
2073 If the QProcess object is already running a process, a warning may be
2074 printed at the console, and the existing process will continue running
2075 unaffected.
2076
2077 \sa processId(), started(), waitForStarted(), setNativeArguments()
2078*/
2079void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
2080{
2081 Q_D(QProcess);
2082 if (d->processState != NotRunning) {
2083 qWarning("QProcess::start: Process is already running");
2084 return;
2085 }
2086 if (program.isEmpty()) {
2087 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2088 return;
2089 }
2090
2091 d->program = program;
2092 d->arguments = arguments;
2093
2094 d->start(mode);
2095}
2096
2097/*!
2098 \since 5.1
2099 \overload
2100
2101 Starts the program set by setProgram() with arguments set by setArguments().
2102 The OpenMode is set to \a mode.
2103
2104 \sa open(), setProgram(), setArguments()
2105 */
2106void QProcess::start(OpenMode mode)
2107{
2108 Q_D(QProcess);
2109 if (d->processState != NotRunning) {
2110 qWarning("QProcess::start: Process is already running");
2111 return;
2112 }
2113 if (d->program.isEmpty()) {
2114 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2115 return;
2116 }
2117
2118 d->start(mode);
2119}
2120
2121/*!
2122 \since 5.10
2123
2124 Starts the program set by setProgram() with arguments set by setArguments()
2125 in a new process, and detaches from it. Returns \c true on success;
2126 otherwise returns \c false. If the calling process exits, the
2127 detached process will continue to run unaffected.
2128
2129 \b{Unix:} The started process will run in its own session and act
2130 like a daemon.
2131
2132 The process will be started in the directory set by setWorkingDirectory().
2133 If workingDirectory() is empty, the working directory is inherited
2134 from the calling process.
2135
2136 \note On QNX, this may cause all application threads to
2137 temporarily freeze.
2138
2139 If the function is successful then *\a pid is set to the process identifier
2140 of the started process. Note that the child process may exit and the PID
2141 may become invalid without notice. Furthermore, after the child process
2142 exits, the same PID may be recycled and used by a completely different
2143 process. User code should be careful when using this variable, especially
2144 if one intends to forcibly terminate the process by operating system means.
2145
2146 Only the following property setters are supported by startDetached():
2147 \list
2148 \li setArguments()
2149 \li setCreateProcessArgumentsModifier()
2150 \li setNativeArguments()
2151 \li setProcessEnvironment()
2152 \li setProgram()
2153 \li setStandardErrorFile()
2154 \li setStandardInputFile()
2155 \li setStandardOutputFile()
2156 \li setWorkingDirectory()
2157 \endlist
2158 All other properties of the QProcess object are ignored.
2159
2160 \note The called process inherits the console window of the calling
2161 process. To suppress console output, redirect standard/error output to
2162 QProcess::nullDevice().
2163
2164 \sa start()
2165 \sa startDetached(const QString &program, const QStringList &arguments,
2166 const QString &workingDirectory, qint64 *pid)
2167 \sa startDetached(const QString &command)
2168*/
2169bool QProcess::startDetached(qint64 *pid)
2170{
2171 Q_D(QProcess);
2172 if (d->processState != NotRunning) {
2173 qWarning("QProcess::startDetached: Process is already running");
2174 return false;
2175 }
2176 if (d->program.isEmpty()) {
2177 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2178 return false;
2179 }
2180 return d->startDetached(pid);
2181}
2182
2183/*!
2184 Starts the program set by setProgram() with arguments set by setArguments().
2185 The OpenMode is set to \a mode.
2186
2187 This method is an alias for start(), and exists only to fully implement
2188 the interface defined by QIODevice.
2189
2190 \sa start(), setProgram(), setArguments()
2191*/
2192bool QProcess::open(OpenMode mode)
2193{
2194 Q_D(QProcess);
2195 if (d->processState != NotRunning) {
2196 qWarning("QProcess::start: Process is already running");
2197 return false;
2198 }
2199 if (d->program.isEmpty()) {
2200 qWarning("QProcess::start: program not set");
2201 return false;
2202 }
2203
2204 d->start(mode);
2205 return true;
2206}
2207
2208void QProcessPrivate::start(QIODevice::OpenMode mode)
2209{
2210 Q_Q(QProcess);
2211#if defined QPROCESS_DEBUG
2212 qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
2213#endif
2214
2215 if (stdinChannel.type != QProcessPrivate::Channel::Normal)
2216 mode &= ~QIODevice::WriteOnly; // not open for writing
2217 if (stdoutChannel.type != QProcessPrivate::Channel::Normal &&
2218 (stderrChannel.type != QProcessPrivate::Channel::Normal ||
2219 processChannelMode == QProcess::MergedChannels))
2220 mode &= ~QIODevice::ReadOnly; // not open for reading
2221 if (mode == 0)
2222 mode = QIODevice::Unbuffered;
2223 if ((mode & QIODevice::ReadOnly) == 0) {
2224 if (stdoutChannel.type == QProcessPrivate::Channel::Normal)
2225 q->setStandardOutputFile(q->nullDevice());
2226 if (stderrChannel.type == QProcessPrivate::Channel::Normal
2227 && processChannelMode != QProcess::MergedChannels)
2228 q->setStandardErrorFile(q->nullDevice());
2229 }
2230
2231 q->QIODevice::open(mode);
2232
2233 if (q->isReadable() && processChannelMode != QProcess::MergedChannels)
2234 setReadChannelCount(2);
2235
2236 stdinChannel.closed = false;
2237 stdoutChannel.closed = false;
2238 stderrChannel.closed = false;
2239
2240 exitCode = 0;
2241 exitStatus = QProcess::NormalExit;
2242 processError = QProcess::UnknownError;
2243 errorString.clear();
2244 startProcess();
2245}
2246
2247
2248static QStringList parseCombinedArgString(const QString &program)
2249{
2250 QStringList args;
2251 QString tmp;
2252 int quoteCount = 0;
2253 bool inQuote = false;
2254
2255 // handle quoting. tokens can be surrounded by double quotes
2256 // "hello world". three consecutive double quotes represent
2257 // the quote character itself.
2258 for (int i = 0; i < program.size(); ++i) {
2259 if (program.at(i) == QLatin1Char('"')) {
2260 ++quoteCount;
2261 if (quoteCount == 3) {
2262 // third consecutive quote
2263 quoteCount = 0;
2264 tmp += program.at(i);
2265 }
2266 continue;
2267 }
2268 if (quoteCount) {
2269 if (quoteCount == 1)
2270 inQuote = !inQuote;
2271 quoteCount = 0;
2272 }
2273 if (!inQuote && program.at(i).isSpace()) {
2274 if (!tmp.isEmpty()) {
2275 args += tmp;
2276 tmp.clear();
2277 }
2278 } else {
2279 tmp += program.at(i);
2280 }
2281 }
2282 if (!tmp.isEmpty())
2283 args += tmp;
2284
2285 return args;
2286}
2287
2288/*!
2289 \overload
2290
2291 Starts the command \a command in a new process.
2292 The OpenMode is set to \a mode.
2293
2294 \a command is a single string of text containing both the program name
2295 and its arguments. The arguments are separated by one or more spaces.
2296 For example:
2297
2298 \snippet code/src_corelib_io_qprocess.cpp 5
2299
2300 Arguments containing spaces must be quoted to be correctly supplied to
2301 the new process. For example:
2302
2303 \snippet code/src_corelib_io_qprocess.cpp 6
2304
2305 Literal quotes in the \a command string are represented by triple quotes.
2306 For example:
2307
2308 \snippet code/src_corelib_io_qprocess.cpp 7
2309
2310 After the \a command string has been split and unquoted, this function
2311 behaves like the overload which takes the arguments as a string list.
2312
2313 You can disable this overload by defining \c
2314 QT_NO_PROCESS_COMBINED_ARGUMENT_START when you compile your applications.
2315 This can be useful if you want to ensure that you are not splitting arguments
2316 unintentionally, for example. In virtually all cases, using the other overload
2317 is the preferred method.
2318
2319 On operating systems where the system API for passing command line
2320 arguments to a subprocess natively uses a single string (Windows), one can
2321 conceive command lines which cannot be passed via QProcess's portable
2322 list-based API. In these rare cases you need to use setProgram() and
2323 setNativeArguments() instead of this function.
2324
2325*/
2326#if !defined(QT_NO_PROCESS_COMBINED_ARGUMENT_START)
2327void QProcess::start(const QString &command, OpenMode mode)
2328{
2329 QStringList args = parseCombinedArgString(command);
2330 if (args.isEmpty()) {
2331 Q_D(QProcess);
2332 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2333 return;
2334 }
2335
2336 const QString prog = args.takeFirst();
2337
2338 start(prog, args, mode);
2339}
2340#endif
2341
2342/*!
2343 \since 5.0
2344
2345 Returns the program the process was last started with.
2346
2347 \sa start()
2348*/
2349QString QProcess::program() const
2350{
2351 Q_D(const QProcess);
2352 return d->program;
2353}
2354
2355/*!
2356 \since 5.1
2357
2358 Set the \a program to use when starting the process.
2359 This function must be called before start().
2360
2361 \sa start(), setArguments(), program()
2362*/
2363void QProcess::setProgram(const QString &program)
2364{
2365 Q_D(QProcess);
2366 if (d->processState != NotRunning) {
2367 qWarning("QProcess::setProgram: Process is already running");
2368 return;
2369 }
2370 d->program = program;
2371}
2372
2373/*!
2374 \since 5.0
2375
2376 Returns the command line arguments the process was last started with.
2377
2378 \sa start()
2379*/
2380QStringList QProcess::arguments() const
2381{
2382 Q_D(const QProcess);
2383 return d->arguments;
2384}
2385
2386/*!
2387 \since 5.1
2388
2389 Set the \a arguments to pass to the called program when starting the process.
2390 This function must be called before start().
2391
2392 \sa start(), setProgram(), arguments()
2393*/
2394void QProcess::setArguments(const QStringList &arguments)
2395{
2396 Q_D(QProcess);
2397 if (d->processState != NotRunning) {
2398 qWarning("QProcess::setProgram: Process is already running");
2399 return;
2400 }
2401 d->arguments = arguments;
2402}
2403
2404/*!
2405 Attempts to terminate the process.
2406
2407 The process may not exit as a result of calling this function (it is given
2408 the chance to prompt the user for any unsaved files, etc).
2409
2410 On Windows, terminate() posts a WM_CLOSE message to all top-level windows
2411 of the process and then to the main thread of the process itself. On Unix
2412 and \macos the \c SIGTERM signal is sent.
2413
2414 Console applications on Windows that do not run an event loop, or whose
2415 event loop does not handle the WM_CLOSE message, can only be terminated by
2416 calling kill().
2417
2418 \sa kill()
2419*/
2420void QProcess::terminate()
2421{
2422 Q_D(QProcess);
2423 d->terminateProcess();
2424}
2425
2426/*!
2427 Kills the current process, causing it to exit immediately.
2428
2429 On Windows, kill() uses TerminateProcess, and on Unix and \macos, the
2430 SIGKILL signal is sent to the process.
2431
2432 \sa terminate()
2433*/
2434void QProcess::kill()
2435{
2436 Q_D(QProcess);
2437 d->killProcess();
2438}
2439
2440/*!
2441 Returns the exit code of the last process that finished.
2442
2443 This value is not valid unless exitStatus() returns NormalExit.
2444*/
2445int QProcess::exitCode() const
2446{
2447 Q_D(const QProcess);
2448 return d->exitCode;
2449}
2450
2451/*!
2452 \since 4.1
2453
2454 Returns the exit status of the last process that finished.
2455
2456 On Windows, if the process was terminated with TerminateProcess() from
2457 another application, this function will still return NormalExit
2458 unless the exit code is less than 0.
2459*/
2460QProcess::ExitStatus QProcess::exitStatus() const
2461{
2462 Q_D(const QProcess);
2463 return d->exitStatus;
2464}
2465
2466/*!
2467 Starts the program \a program with the arguments \a arguments in a
2468 new process, waits for it to finish, and then returns the exit
2469 code of the process. Any data the new process writes to the
2470 console is forwarded to the calling process.
2471
2472 The environment and working directory are inherited from the calling
2473 process.
2474
2475 Argument handling is identical to the respective start() overload.
2476
2477 If the process cannot be started, -2 is returned. If the process
2478 crashes, -1 is returned. Otherwise, the process' exit code is
2479 returned.
2480
2481 \sa start()
2482*/
2483int QProcess::execute(const QString &program, const QStringList &arguments)
2484{
2485 QProcess process;
2486 process.setProcessChannelMode(ForwardedChannels);
2487 process.start(program, arguments);
2488 if (!process.waitForFinished(-1) || process.error() == FailedToStart)
2489 return -2;
2490 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2491}
2492
2493/*!
2494 \overload
2495
2496 Starts the program \a command in a new process, waits for it to finish,
2497 and then returns the exit code.
2498
2499 Argument handling is identical to the respective start() overload.
2500
2501 After the \a command string has been split and unquoted, this function
2502 behaves like the overload which takes the arguments as a string list.
2503
2504 \sa start()
2505*/
2506int QProcess::execute(const QString &command)
2507{
2508 QProcess process;
2509 process.setProcessChannelMode(ForwardedChannels);
2510 process.start(command);
2511 if (!process.waitForFinished(-1) || process.error() == FailedToStart)
2512 return -2;
2513 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2514}
2515
2516/*!
2517 \overload startDetached()
2518
2519 Starts the program \a program with the arguments \a arguments in a
2520 new process, and detaches from it. Returns \c true on success;
2521 otherwise returns \c false. If the calling process exits, the
2522 detached process will continue to run unaffected.
2523
2524 Argument handling is identical to the respective start() overload.
2525
2526 The process will be started in the directory \a workingDirectory.
2527 If \a workingDirectory is empty, the working directory is inherited
2528 from the calling process.
2529
2530 If the function is successful then *\a pid is set to the process
2531 identifier of the started process.
2532
2533 \sa start()
2534*/
2535bool QProcess::startDetached(const QString &program,
2536 const QStringList &arguments,
2537 const QString &workingDirectory,
2538 qint64 *pid)
2539{
2540 QProcess process;
2541 process.setProgram(program);
2542 process.setArguments(arguments);
2543 process.setWorkingDirectory(workingDirectory);
2544 return process.startDetached(pid);
2545}
2546
2547/*!
2548 \internal
2549*/
2550bool QProcess::startDetached(const QString &program,
2551 const QStringList &arguments)
2552{
2553 QProcess process;
2554 process.setProgram(program);
2555 process.setArguments(arguments);
2556 return process.startDetached();
2557}
2558
2559/*!
2560 \overload startDetached()
2561
2562 Starts the command \a command in a new process, and detaches from it.
2563 Returns \c true on success; otherwise returns \c false.
2564
2565 Argument handling is identical to the respective start() overload.
2566
2567 After the \a command string has been split and unquoted, this function
2568 behaves like the overload which takes the arguments as a string list.
2569
2570 \sa start(const QString &command, QIODevice::OpenMode mode)
2571*/
2572bool QProcess::startDetached(const QString &command)
2573{
2574 QStringList args = parseCombinedArgString(command);
2575 if (args.isEmpty())
2576 return false;
2577
2578 QProcess process;
2579 process.setProgram(args.takeFirst());
2580 process.setArguments(args);
2581 return process.startDetached();
2582}
2583
2584QT_BEGIN_INCLUDE_NAMESPACE
2585#if defined(Q_OS_MACX)
2586# include <crt_externs.h>
2587# define environ (*_NSGetEnviron())
2588#elif defined(QT_PLATFORM_UIKIT)
2589 static char *qt_empty_environ[] = { 0 };
2590#define environ qt_empty_environ
2591#elif !defined(Q_OS_WIN)
2592 extern char **environ;
2593#endif
2594QT_END_INCLUDE_NAMESPACE
2595
2596/*!
2597 \since 4.1
2598
2599 Returns the environment of the calling process as a list of
2600 key=value pairs. Example:
2601
2602 \snippet code/src_corelib_io_qprocess.cpp 8
2603
2604 This function does not cache the system environment. Therefore, it's
2605 possible to obtain an updated version of the environment if low-level C
2606 library functions like \tt setenv or \tt putenv have been called.
2607
2608 However, note that repeated calls to this function will recreate the
2609 list of environment variables, which is a non-trivial operation.
2610
2611 \note For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
2612
2613 \sa QProcessEnvironment::systemEnvironment(), setProcessEnvironment()
2614*/
2615QStringList QProcess::systemEnvironment()
2616{
2617 QStringList tmp;
2618 char *entry = 0;
2619 int count = 0;
2620 while ((entry = environ[count++]))
2621 tmp << QString::fromLocal8Bit(entry);
2622 return tmp;
2623}
2624
2625/*!
2626 \fn QProcessEnvironment QProcessEnvironment::systemEnvironment()
2627
2628 \since 4.6
2629
2630 \brief The systemEnvironment function returns the environment of
2631 the calling process.
2632
2633 It is returned as a QProcessEnvironment. This function does not
2634 cache the system environment. Therefore, it's possible to obtain
2635 an updated version of the environment if low-level C library
2636 functions like \tt setenv or \tt putenv have been called.
2637
2638 However, note that repeated calls to this function will recreate the
2639 QProcessEnvironment object, which is a non-trivial operation.
2640
2641 \sa QProcess::systemEnvironment()
2642*/
2643
2644/*!
2645 \since 5.2
2646
2647 \brief The null device of the operating system.
2648
2649 The returned file path uses native directory separators.
2650
2651 \sa QProcess::setStandardInputFile(), QProcess::setStandardOutputFile(),
2652 QProcess::setStandardErrorFile()
2653*/
2654QString QProcess::nullDevice()
2655{
2656#ifdef Q_OS_WIN
2657 return QStringLiteral("\\\\.\\NUL");
2658#elif defined(_PATH_DEVNULL)
2659 return QStringLiteral(_PATH_DEVNULL);
2660#else
2661 return QStringLiteral("/dev/null");
2662#endif
2663}
2664
2665/*!
2666 \typedef Q_PID
2667 \relates QProcess
2668
2669 Typedef for the identifiers used to represent processes on the underlying
2670 platform. On Unix, this corresponds to \l qint64; on Windows, it
2671 corresponds to \c{_PROCESS_INFORMATION*}.
2672
2673 \sa QProcess::pid()
2674*/
2675
2676#endif // QT_CONFIG(process)
2677
2678QT_END_NAMESPACE
2679
2680#include "moc_qprocess.cpp"
2681