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
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
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 Blocks until the process has started and the started() signal has
2068 been emitted, or until \a msecs milliseconds have passed.
2069
2070 Returns \c true if the process was started successfully; otherwise
2071 returns \c false (if the operation timed out or if an error
2072 occurred). If the process had already started successfully before this
2073 function, it returns immediately.
2074
2075 This function can operate without an event loop. It is
2076 useful when writing non-GUI applications and when performing
2077 I/O operations in a non-GUI thread.
2078
2079 \warning Calling this function from the main (GUI) thread
2080 might cause your user interface to freeze.
2081
2082 If msecs is -1, this function will not time out.
2083
2084 \sa started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
2085*/
2086bool QProcess::waitForStarted(int msecs)
2087{
2088 Q_D(QProcess);
2089 if (d->processState == QProcess::Starting)
2090 return d->waitForStarted(QDeadlineTimer(msecs));
2091
2092 return d->processState == QProcess::Running;
2093}
2094
2095/*! \reimp
2096*/
2097bool QProcess::waitForReadyRead(int msecs)
2098{
2099 Q_D(QProcess);
2100
2101 if (d->processState == QProcess::NotRunning)
2102 return false;
2103 if (d->currentReadChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
2104 return false;
2105 if (d->currentReadChannel == QProcess::StandardError && d->stderrChannel.closed)
2106 return false;
2107
2108 QDeadlineTimer deadline(msecs);
2109 if (d->processState == QProcess::Starting) {
2110 bool started = d->waitForStarted(deadline);
2111 if (!started)
2112 return false;
2113 }
2114
2115 return d->waitForReadyRead(deadline);
2116}
2117
2118/*! \reimp
2119*/
2120bool QProcess::waitForBytesWritten(int msecs)
2121{
2122 Q_D(QProcess);
2123 if (d->processState == QProcess::NotRunning)
2124 return false;
2125
2126 QDeadlineTimer deadline(msecs);
2127 if (d->processState == QProcess::Starting) {
2128 bool started = d->waitForStarted(deadline);
2129 if (!started)
2130 return false;
2131 }
2132
2133 return d->waitForBytesWritten(deadline);
2134}
2135
2136/*!
2137 Blocks until the process has finished and the finished() signal
2138 has been emitted, or until \a msecs milliseconds have passed.
2139
2140 Returns \c true if the process finished; otherwise returns \c false (if
2141 the operation timed out, if an error occurred, or if this QProcess
2142 is already finished).
2143
2144 This function can operate without an event loop. It is
2145 useful when writing non-GUI applications and when performing
2146 I/O operations in a non-GUI thread.
2147
2148 \warning Calling this function from the main (GUI) thread
2149 might cause your user interface to freeze.
2150
2151 If msecs is -1, this function will not time out.
2152
2153 \sa finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
2154*/
2155bool QProcess::waitForFinished(int msecs)
2156{
2157 Q_D(QProcess);
2158 if (d->processState == QProcess::NotRunning)
2159 return false;
2160
2161 QDeadlineTimer deadline(msecs);
2162 if (d->processState == QProcess::Starting) {
2163 bool started = d->waitForStarted(deadline);
2164 if (!started)
2165 return false;
2166 }
2167
2168 return d->waitForFinished(deadline);
2169}
2170
2171/*!
2172 Sets the current state of the QProcess to the \a state specified.
2173
2174 \sa state()
2175*/
2176void QProcess::setProcessState(ProcessState state)
2177{
2178 Q_D(QProcess);
2179 if (d->processState == state)
2180 return;
2181 d->processState = state;
2182 emit stateChanged(state, QPrivateSignal());
2183}
2184
2185#if QT_VERSION < QT_VERSION_CHECK(7,0,0)
2186/*!
2187 \internal
2188*/
2189auto QProcess::setupChildProcess() -> Use_setChildProcessModifier_Instead
2190{
2191 Q_UNREACHABLE_RETURN({});
2192}
2193#endif
2194
2195/*! \reimp
2196*/
2197qint64 QProcess::readData(char *data, qint64 maxlen)
2198{
2199 Q_D(QProcess);
2200 Q_UNUSED(data);
2201 if (!maxlen)
2202 return 0;
2203 if (d->processState == QProcess::NotRunning)
2204 return -1; // EOF
2205 return 0;
2206}
2207
2208/*!
2209 Regardless of the current read channel, this function returns all
2210 data available from the standard output of the process as a
2211 QByteArray.
2212
2213 \sa readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
2214*/
2215QByteArray QProcess::readAllStandardOutput()
2216{
2217 ProcessChannel tmp = readChannel();
2218 setReadChannel(StandardOutput);
2219 QByteArray data = readAll();
2220 setReadChannel(tmp);
2221 return data;
2222}
2223
2224/*!
2225 Regardless of the current read channel, this function returns all
2226 data available from the standard error of the process as a
2227 QByteArray.
2228
2229 \sa readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
2230*/
2231QByteArray QProcess::readAllStandardError()
2232{
2233 Q_D(QProcess);
2234 QByteArray data;
2235 if (d->processChannelMode == MergedChannels) {
2236 qWarning("QProcess::readAllStandardError: Called with MergedChannels");
2237 } else {
2238 ProcessChannel tmp = readChannel();
2239 setReadChannel(StandardError);
2240 data = readAll();
2241 setReadChannel(tmp);
2242 }
2243 return data;
2244}
2245
2246/*!
2247 Starts the given \a program in a new process, passing the command line
2248 arguments in \a arguments. See setProgram() for information about how
2249 QProcess searches for the executable to be run. The OpenMode is set to \a
2250 mode. No further splitting of the arguments is performed.
2251
2252 The QProcess object will immediately enter the Starting state. If the
2253 process starts successfully, QProcess will emit started(); otherwise,
2254 errorOccurred() will be emitted. Do note that on platforms that are able to
2255 start child processes synchronously (notably Windows), those signals will
2256 be emitted before this function returns and this QProcess object will
2257 transition to either QProcess::Running or QProcess::NotRunning state,
2258 respectively. On others paltforms, the started() and errorOccurred()
2259 signals will be delayed.
2260
2261 Call waitForStarted() to make sure the process has started (or has failed
2262 to start) and those signals have been emitted. It is safe to call that
2263 function even if the process starting state is already known, though the
2264 signal will not be emitted again.
2265
2266 \b{Windows:} The arguments are quoted and joined into a command line
2267 that is compatible with the \c CommandLineToArgvW() Windows function.
2268 For programs that have different command line quoting requirements,
2269 you need to use setNativeArguments(). One notable program that does
2270 not follow the \c CommandLineToArgvW() rules is cmd.exe and, by
2271 consequence, all batch scripts.
2272
2273 If the QProcess object is already running a process, a warning may be
2274 printed at the console, and the existing process will continue running
2275 unaffected.
2276
2277 \note Success at starting the child process only implies the operating
2278 system has successfully created the process and assigned the resources
2279 every process has, such as its process ID. The child process may crash or
2280 otherwise fail very early and thus not produce its expected output. On most
2281 operating systems, this may include dynamic linking errors.
2282
2283 \sa processId(), started(), waitForStarted(), setNativeArguments()
2284*/
2285void QProcess::start(const QString &program, const QStringList &arguments, OpenMode mode)
2286{
2287 Q_D(QProcess);
2288 if (d->processState != NotRunning) {
2289 qWarning("QProcess::start: Process is already running");
2290 return;
2291 }
2292 if (program.isEmpty()) {
2293 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2294 return;
2295 }
2296
2297 d->program = program;
2298 d->arguments = arguments;
2299
2300 d->start(mode);
2301}
2302
2303/*!
2304 \since 5.1
2305 \overload
2306
2307 Starts the program set by setProgram() with arguments set by setArguments().
2308 The OpenMode is set to \a mode.
2309
2310 \sa open(), setProgram(), setArguments()
2311 */
2312void QProcess::start(OpenMode mode)
2313{
2314 Q_D(QProcess);
2315 if (d->processState != NotRunning) {
2316 qWarning("QProcess::start: Process is already running");
2317 return;
2318 }
2319 if (d->program.isEmpty()) {
2320 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2321 return;
2322 }
2323
2324 d->start(mode);
2325}
2326
2327/*!
2328 \since 6.0
2329
2330 Starts the command \a command in a new process.
2331 The OpenMode is set to \a mode.
2332
2333 \a command is a single string of text containing both the program name
2334 and its arguments. The arguments are separated by one or more spaces.
2335 For example:
2336
2337 \snippet code/src_corelib_io_qprocess.cpp 5
2338
2339 Arguments containing spaces must be quoted to be correctly supplied to
2340 the new process. For example:
2341
2342 \snippet code/src_corelib_io_qprocess.cpp 6
2343
2344 Literal quotes in the \a command string are represented by triple quotes.
2345 For example:
2346
2347 \snippet code/src_corelib_io_qprocess.cpp 7
2348
2349 After the \a command string has been split and unquoted, this function
2350 behaves like start().
2351
2352 On operating systems where the system API for passing command line
2353 arguments to a subprocess natively uses a single string (Windows), one can
2354 conceive command lines which cannot be passed via QProcess's portable
2355 list-based API. In these rare cases you need to use setProgram() and
2356 setNativeArguments() instead of this function.
2357
2358 \sa splitCommand()
2359 \sa start()
2360 */
2361void QProcess::startCommand(const QString &command, OpenMode mode)
2362{
2363 QStringList args = splitCommand(command);
2364 if (args.isEmpty()) {
2365 qWarning("QProcess::startCommand: empty or whitespace-only command was provided");
2366 return;
2367 }
2368 const QString program = args.takeFirst();
2369 // AXIVION Next Line Qt-Security-QProcessStart: implementation
2370 start(program, args, mode);
2371}
2372
2373/*!
2374 \since 5.10
2375
2376 Starts the program set by setProgram() with arguments set by setArguments()
2377 in a new process, and detaches from it. Returns \c true on success;
2378 otherwise returns \c false. If the calling process exits, the
2379 detached process will continue to run unaffected.
2380
2381 \b{Unix:} The started process will run in its own session and act
2382 like a daemon.
2383
2384 The process will be started in the directory set by setWorkingDirectory().
2385 If workingDirectory() is empty, the working directory is inherited
2386 from the calling process.
2387
2388 If the function is successful then *\a pid is set to the process identifier
2389 of the started process; otherwise, it's set to -1. Note that the child
2390 process may exit and the PID may become invalid without notice.
2391 Furthermore, after the child process exits, the same PID may be recycled
2392 and used by a completely different process. User code should be careful
2393 when using this variable, especially if one intends to forcibly terminate
2394 the process by operating system means.
2395
2396 Only the following property setters are supported by startDetached():
2397 \list
2398 \li setArguments()
2399 \li setCreateProcessArgumentsModifier()
2400 \li setNativeArguments()
2401 \li setProcessEnvironment()
2402 \li setProgram()
2403 \li setStandardErrorFile()
2404 \li setStandardInputFile()
2405 \li setStandardOutputFile()
2406 \li setProcessChannelMode(QProcess::MergedChannels)
2407 \li setStandardOutputProcess()
2408 \li setWorkingDirectory()
2409 \endlist
2410 All other properties of the QProcess object are ignored.
2411
2412 \note The called process inherits the console window of the calling
2413 process. To suppress console output, redirect standard/error output to
2414 QProcess::nullDevice().
2415
2416 \sa start()
2417 \sa startDetached(const QString &program, const QStringList &arguments,
2418 const QString &workingDirectory, qint64 *pid)
2419*/
2420bool QProcess::startDetached(qint64 *pid)
2421{
2422 Q_D(QProcess);
2423 if (d->processState != NotRunning) {
2424 qWarning("QProcess::startDetached: Process is already running");
2425 return false;
2426 }
2427 if (d->program.isEmpty()) {
2428 d->setErrorAndEmit(QProcess::FailedToStart, tr("No program defined"));
2429 return false;
2430 }
2431 return d->startDetached(pid);
2432}
2433
2434/*!
2435 Starts the program set by setProgram() with arguments set by setArguments().
2436 The OpenMode is set to \a mode.
2437
2438 This method is an alias for start(), and exists only to fully implement
2439 the interface defined by QIODevice.
2440
2441 Returns \c true if the program has been started.
2442
2443 \sa start(), setProgram(), setArguments()
2444*/
2445bool QProcess::open(OpenMode mode)
2446{
2447 Q_D(QProcess);
2448 if (d->processState != NotRunning) {
2449 qWarning("QProcess::start: Process is already running");
2450 return false;
2451 }
2452 if (d->program.isEmpty()) {
2453 qWarning("QProcess::start: program not set");
2454 return false;
2455 }
2456
2457 d->start(mode);
2458 return true;
2459}
2460
2461void QProcessPrivate::start(QIODevice::OpenMode mode)
2462{
2463 Q_Q(QProcess);
2464#if defined QPROCESS_DEBUG
2465 qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
2466#endif
2467
2468 if (stdinChannel.type != QProcessPrivate::Channel::Normal)
2469 mode &= ~QIODevice::WriteOnly; // not open for writing
2470 if (stdoutChannel.type != QProcessPrivate::Channel::Normal &&
2471 (stderrChannel.type != QProcessPrivate::Channel::Normal ||
2472 processChannelMode == QProcess::MergedChannels))
2473 mode &= ~QIODevice::ReadOnly; // not open for reading
2474 if (mode == 0)
2475 mode = QIODevice::Unbuffered;
2476 if ((mode & QIODevice::ReadOnly) == 0) {
2477 if (stdoutChannel.type == QProcessPrivate::Channel::Normal)
2478 q->setStandardOutputFile(q->nullDevice());
2479 if (stderrChannel.type == QProcessPrivate::Channel::Normal
2480 && processChannelMode != QProcess::MergedChannels)
2481 q->setStandardErrorFile(q->nullDevice());
2482 }
2483
2484 q->QIODevice::open(mode);
2485
2486 if (q->isReadable() && processChannelMode != QProcess::MergedChannels)
2487 setReadChannelCount(2);
2488
2489 stdinChannel.closed = false;
2490 stdoutChannel.closed = false;
2491 stderrChannel.closed = false;
2492
2493 exitCode = 0;
2494 exitStatus = QProcess::NormalExit;
2495 processError = QProcess::UnknownError;
2496 errorString.clear();
2497 startProcess();
2498}
2499#endif // QT_CONFIG(process)
2500
2501/*!
2502 \since 5.15
2503
2504 Splits the string \a command into a list of tokens, and returns
2505 the list.
2506
2507 Tokens with spaces can be surrounded by double quotes; three
2508 consecutive double quotes represent the quote character itself.
2509*/
2510QStringList QProcess::splitCommand(QStringView command)
2511{
2512 QStringList args;
2513 QString tmp;
2514 int quoteCount = 0;
2515 bool inQuote = false;
2516
2517 // handle quoting. tokens can be surrounded by double quotes
2518 // "hello world". three consecutive double quotes represent
2519 // the quote character itself.
2520 for (int i = 0; i < command.size(); ++i) {
2521 if (command.at(i) == u'"') {
2522 ++quoteCount;
2523 if (quoteCount == 3) {
2524 // third consecutive quote
2525 quoteCount = 0;
2526 tmp += command.at(i);
2527 }
2528 continue;
2529 }
2530 if (quoteCount) {
2531 if (quoteCount == 1)
2532 inQuote = !inQuote;
2533 quoteCount = 0;
2534 }
2535 if (!inQuote && command.at(i).isSpace()) {
2536 if (!tmp.isEmpty()) {
2537 args += tmp;
2538 tmp.clear();
2539 }
2540 } else {
2541 tmp += command.at(i);
2542 }
2543 }
2544 if (!tmp.isEmpty())
2545 args += tmp;
2546
2547 return args;
2548}
2549
2550#if QT_CONFIG(process)
2551/*!
2552 \since 5.0
2553
2554 Returns the program the process was last started with.
2555
2556 \sa start()
2557*/
2558QString QProcess::program() const
2559{
2560 Q_D(const QProcess);
2561 return d->program;
2562}
2563
2564/*!
2565 \since 5.1
2566
2567 Set the \a program to use when starting the process.
2568 This function must be called before start().
2569
2570 If \a program is an absolute path, it specifies the exact executable that
2571 will be launched. Relative paths will be resolved in a platform-specific
2572 manner, which includes searching the \c PATH environment variable (see
2573 \l{Finding the Executable} for details).
2574
2575 \sa start(), setArguments(), program(), QStandardPaths::findExecutable()
2576*/
2577void QProcess::setProgram(const QString &program)
2578{
2579 Q_D(QProcess);
2580 if (d->processState != NotRunning) {
2581 qWarning("QProcess::setProgram: Process is already running");
2582 return;
2583 }
2584 d->program = program;
2585}
2586
2587/*!
2588 \since 5.0
2589
2590 Returns the command line arguments the process was last started with.
2591
2592 \sa start()
2593*/
2594QStringList QProcess::arguments() const
2595{
2596 Q_D(const QProcess);
2597 return d->arguments;
2598}
2599
2600/*!
2601 \since 5.1
2602
2603 Set the \a arguments to pass to the called program when starting the process.
2604 This function must be called before start().
2605
2606 \sa start(), setProgram(), arguments()
2607*/
2608void QProcess::setArguments(const QStringList &arguments)
2609{
2610 Q_D(QProcess);
2611 if (d->processState != NotRunning) {
2612 qWarning("QProcess::setProgram: Process is already running");
2613 return;
2614 }
2615 d->arguments = arguments;
2616}
2617
2618/*!
2619 Attempts to terminate the process.
2620
2621 The process may not exit as a result of calling this function (it is given
2622 the chance to prompt the user for any unsaved files, etc).
2623
2624 On Windows, terminate() posts a WM_CLOSE message to all top-level windows
2625 of the process and then to the main thread of the process itself. On Unix
2626 and \macos the \c SIGTERM signal is sent.
2627
2628 Console applications on Windows that do not run an event loop, or whose
2629 event loop does not handle the WM_CLOSE message, can only be terminated by
2630 calling kill().
2631
2632 \sa kill()
2633*/
2634void QProcess::terminate()
2635{
2636 Q_D(QProcess);
2637 d->terminateProcess();
2638}
2639
2640/*!
2641 Kills the current process, causing it to exit immediately.
2642
2643 On Windows, kill() uses TerminateProcess, and on Unix and \macos, the
2644 SIGKILL signal is sent to the process.
2645
2646 \sa terminate()
2647*/
2648void QProcess::kill()
2649{
2650 Q_D(QProcess);
2651 d->killProcess();
2652}
2653
2654/*!
2655 Returns the exit code of the last process that finished.
2656
2657 This value is not valid unless exitStatus() returns NormalExit.
2658*/
2659int QProcess::exitCode() const
2660{
2661 Q_D(const QProcess);
2662 return d->exitCode;
2663}
2664
2665/*!
2666 \since 4.1
2667
2668 Returns the exit status of the last process that finished.
2669
2670 On Windows, if the process was terminated with TerminateProcess() from
2671 another application, this function will still return NormalExit
2672 unless the exit code is less than 0.
2673*/
2674QProcess::ExitStatus QProcess::exitStatus() const
2675{
2676 Q_D(const QProcess);
2677 return ExitStatus(d->exitStatus);
2678}
2679
2680/*!
2681 Starts the program \a program with the arguments \a arguments in a
2682 new process, waits for it to finish, and then returns the exit
2683 code of the process. Any data the new process writes to the
2684 console is forwarded to the calling process.
2685
2686 The environment and working directory are inherited from the calling
2687 process.
2688
2689 Argument handling is identical to the respective start() overload.
2690
2691 If the process cannot be started, -2 is returned. If the process
2692 crashes, -1 is returned. Otherwise, the process' exit code is
2693 returned.
2694
2695 \sa start()
2696*/
2697int QProcess::execute(const QString &program, const QStringList &arguments)
2698{
2699 QProcess process;
2700 process.setProcessChannelMode(ForwardedChannels);
2701 // AXIVION Next Line Qt-Security-QProcessStart: implementation
2702 process.start(program, arguments);
2703 if (!process.waitForFinished(-1) || process.error() == FailedToStart)
2704 return -2;
2705 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2706}
2707
2708/*!
2709 \overload startDetached()
2710
2711 Starts the program \a program with the arguments \a arguments in a
2712 new process, and detaches from it. Returns \c true on success;
2713 otherwise returns \c false. If the calling process exits, the
2714 detached process will continue to run unaffected.
2715
2716 Argument handling is identical to the respective start() overload.
2717
2718 The process will be started in the directory \a workingDirectory.
2719 If \a workingDirectory is empty, the working directory is inherited
2720 from the calling process.
2721
2722 If the function is successful then *\a pid is set to the process
2723 identifier of the started process.
2724
2725 \sa start()
2726*/
2727bool QProcess::startDetached(const QString &program,
2728 const QStringList &arguments,
2729 const QString &workingDirectory,
2730 qint64 *pid)
2731{
2732 QProcess process;
2733 // AXIVION DISABLE Style Qt-Security-QProcessStart: implementation
2734 process.setProgram(program);
2735 process.setArguments(arguments);
2736 process.setWorkingDirectory(workingDirectory);
2737 return process.startDetached(pid);
2738 // AXIVION ENABLE Style Qt-Security-QProcessStart
2739}
2740
2741/*!
2742 \since 4.1
2743
2744 Returns the environment of the calling process as a list of
2745 key=value pairs. Example:
2746
2747 \snippet code/src_corelib_io_qprocess.cpp 8
2748
2749 This function does not cache the system environment. Therefore, it's
2750 possible to obtain an updated version of the environment if low-level C
2751 library functions like \tt setenv or \tt putenv have been called.
2752
2753 However, note that repeated calls to this function will recreate the
2754 list of environment variables, which is a non-trivial operation.
2755
2756 \note For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
2757
2758 \sa QProcessEnvironment::systemEnvironment(), setProcessEnvironment()
2759*/
2760QStringList QProcess::systemEnvironment()
2761{
2762 return QProcessEnvironment::systemEnvironment().toStringList();
2763}
2764
2765/*!
2766 \fn QProcessEnvironment QProcessEnvironment::systemEnvironment()
2767
2768 \since 4.6
2769
2770 \brief The systemEnvironment function returns the environment of
2771 the calling process.
2772
2773 It is returned as a QProcessEnvironment. This function does not
2774 cache the system environment. Therefore, it's possible to obtain
2775 an updated version of the environment if low-level C library
2776 functions like \tt setenv or \tt putenv have been called.
2777
2778 However, note that repeated calls to this function will recreate the
2779 QProcessEnvironment object, which is a non-trivial operation.
2780
2781 \sa QProcess::systemEnvironment()
2782*/
2783
2784/*!
2785 \since 5.2
2786
2787 \brief The null device of the operating system.
2788
2789 The returned file path uses native directory separators.
2790
2791 \sa QProcess::setStandardInputFile(), QProcess::setStandardOutputFile(),
2792 QProcess::setStandardErrorFile()
2793*/
2794QString QProcess::nullDevice()
2795{
2796#ifdef Q_OS_WIN
2797 return QStringLiteral("\\\\.\\NUL");
2798#elif defined(_PATH_DEVNULL)
2799 return QStringLiteral(_PATH_DEVNULL);
2800#else
2801 return QStringLiteral("/dev/null");
2802#endif
2803}
2804
2805#endif // QT_CONFIG(process)
2806
2807QT_END_NAMESPACE
2808
2809#if QT_CONFIG(process)
2810#include "moc_qprocess.cpp"
2811#endif
void insert(const QProcessEnvironmentPrivate &other)
Definition qprocess.cpp:107
QStringList keys() const
Definition qprocess.cpp:96
\inmodule QtCore
Definition qprocess.h:33
Combined button and popup list for selecting options.
#define __has_include(x)
bool comparesEqual(const QFileInfo &lhs, const QFileInfo &rhs)