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