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