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