QProcess Class▲
-
Header: QProcess
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Inherits: QIODevice
-
Group: QProcess is part of Input/Output and Networking
Detailed Description▲
Running a Process▲
To start a process, pass the name and command line arguments of the program you want to run as arguments to start(). Arguments are supplied as individual strings in a QStringList.
Alternatively, you can set the program to run with setProgram() and setArguments(), and then call start() or open().
For example, the following code snippet runs the analog clock example in the Fusion style on X11 platforms by passing strings containing "-style" and "fusion" as two items in the list of arguments:
QObject *
parent;
...
QString program =
"./path/to/Qt/examples/widgets/analogclock"
;
QStringList arguments;
arguments &
lt;&
lt; "-style"
&
lt;&
lt; "fusion"
;
QProcess *
myProcess =
new
QProcess(parent);
myProcess-&
gt;start(program, arguments);
QProcess then enters the Starting state, and when the program has started, QProcess enters the Running state and emits started().
QProcess allows you to treat a process as a sequential I/O device. You can write to and read from the process just as you would access a network connection using QTcpSocket. You can then write to the process's standard input by calling write(), and read the standard output by calling read(), readLine(), and getChar(). Because it inherits QIODevice, QProcess can also be used as an input source for QXmlReader, or for generating data to be uploaded using QNetworkAccessManager.
When the process exits, QProcess reenters the NotRunning state (the initial state), and emits finished().
The finished() signal provides the exit code and exit status of the process as arguments, and you can also call exitCode() to obtain the exit code of the last process that finished, and exitStatus() to obtain its exit status. If an error occurs at any point in time, QProcess will emit the errorOccurred() signal. You can also call error() to find the type of error that occurred last, and state() to find the current process state.
QProcess is not supported on VxWorks, iOS, tvOS, or watchOS.
Finding the Executable▲
The program to be run can be set either by calling setProgram() or directly in the start() call. The effect of calling start() with the program name and arguments is equivalent to calling setProgram() and setArguments() before that function and then calling the overload without those parameters.
QProcess interprets the program name in one of three different ways, similar to how Unix shells and the Windows command interpreter operate in their own command-lines:
-
If the program name is an absolute path, then that is the exact executable that will be launched and QProcess performs no searching.
-
If the program name is a relative path with more than one path component (that is, it contains at least one slash), the starting directory where that relative path is searched is OS-dependent: on Windows, it's the parent process' current working dir, while on Unix it's the one set with setWorkingDirectory().
-
If the program name is a plain file name with no slashes, the behavior is operating-system dependent. On Unix systems, QProcess will search the PATH environment variable; on Windows, the search is performed by the OS and will first the parent process' current directory before the PATH environment variable (see the documentation for CreateProcess for the full list).
To avoid platform-dependent behavior or any issues with how the current application was launched, it is adviseable to always pass an absolute path to the executable to be launched. For auxiliary binaries shipped with the application, one can construct such a path starting with QCoreApplication::applicationDirPath(). Similarly, to explicitly run an executable that is to be found relative to the directory set with setWorkingDirectory(), use a program path starting with "./" or "../" as the case may be.
On Windows, the ".exe" suffix is not required for most uses, except those outlined in the CreateProcess documentation. Additionally, QProcess will convert the Unix-style forward slashes to Windows path backslashes for the program name. This allows code using QProcess to be written in a cross-platform manner, as shown in the examples above.
QProcess does not support directly executing Unix shell or Windows command interpreter built-in functions, such as cmd.exe's dir command or the Bourne shell's export. On Unix, even though many shell built-ins are also provided as separate executables, their behavior may differ from those implemented as built-ins. To run those commands, one should explicitly execute the interpreter with suitable options. For Unix systems, launch "/bin/sh" with two arguments: "-c" and a string with the command-line to be run. For Windows, due to the non-standard way cmd.exe parses its command-line, use setNativeArguments() (for example, "/c dir d:").
Communicating via Channels▲
Processes have two predefined output channels: The standard output channel (stdout) supplies regular console output, and the standard error channel (stderr) usually supplies the errors that are printed by the process. These channels represent two separate streams of data. You can toggle between them by calling setReadChannel(). QProcess emits readyRead() when data is available on the current read channel. It also emits readyReadStandardOutput() when new standard output data is available, and when new standard error data is available, readyReadStandardError() is emitted. Instead of calling read(), readLine(), or getChar(), you can explicitly read all data from either of the two channels by calling readAllStandardOutput() or readAllStandardError().
The terminology for the channels can be misleading. Be aware that the process's output channels correspond to QProcess's read channels, whereas the process's input channels correspond to QProcess's write channels. This is because what we read using QProcess is the process's output, and what we write becomes the process's input.
QProcess can merge the two output channels, so that standard output and standard error data from the running process both use the standard output channel. Call setProcessChannelMode() with MergedChannels before starting the process to activate this feature. You also have the option of forwarding the output of the running process to the calling, main process, by passing ForwardedChannels as the argument. It is also possible to forward only one of the output channels - typically one would use ForwardedErrorChannel, but ForwardedOutputChannel also exists. Note that using channel forwarding is typically a bad idea in GUI applications - you should present errors graphically instead.
Certain processes need special environment settings in order to operate. You can set environment variables for your process by calling setProcessEnvironment(). To set a working directory, call setWorkingDirectory(). By default, processes are run in the current working directory of the calling process.
The positioning and the screen Z-order of windows belonging to GUI applications started with QProcess are controlled by the underlying windowing system. For Qt 5 applications, the positioning can be specified using the -qwindowgeometry command line option; X11 applications generally accept a -geometry command line option.
On QNX, setting the working directory may cause all application threads, with the exception of the QProcess caller thread, to temporarily freeze during the spawning process, owing to a limitation in the operating system.
Synchronous Process API▲
QProcess provides a set of functions which allow it to be used without an event loop, by suspending the calling thread until certain signals are emitted:
-
waitForStarted() blocks until the process has started.
-
waitForReadyRead() blocks until new data is available for reading on the current read channel.
-
waitForBytesWritten() blocks until one payload of data has been written to the process.
-
waitForFinished() blocks until the process has finished.
Calling these functions from the main thread (the thread that calls QApplication::exec()) may cause your user interface to freeze.
The following example runs gzip to compress the string "Qt rocks!", without an event loop:
QProcess gzip;
gzip.start("gzip"
, QStringList() &
lt;&
lt; "-c"
);
if
(!
gzip.waitForStarted())
return
false
;
gzip.write("Qt rocks!"
);
gzip.closeWriteChannel();
if
(!
gzip.waitForFinished())
return
false
;
QByteArray result =
gzip.readAll();
See Also▲
See also QBuffer, QFile, QTcpSocket
Member Type Documentation▲
QProcess::CreateProcessArgumentModifier▲
This typedef is only available on desktop Windows.
On Windows, QProcess uses the Win32 API function CreateProcess to start child processes. While QProcess provides a comfortable way to start processes without worrying about platform details, it is in some cases desirable to fine-tune the parameters that are passed to CreateProcess. This is done by defining a CreateProcessArgumentModifier function and passing it to setCreateProcessArgumentsModifier.
A CreateProcessArgumentModifier function takes one parameter: a pointer to a CreateProcessArguments struct. The members of this struct will be passed to CreateProcess after the CreateProcessArgumentModifier function is called.
The following example demonstrates how to pass custom flags to CreateProcess. When starting a console process B from a console process A, QProcess will reuse the console window of process A for process B by default. In this example, a new console window with a custom color scheme is created for the child process B instead.
QProcess process;
process.setCreateProcessArgumentsModifier([] (QProcess::
CreateProcessArguments *
args)
{
args-&
gt;flags |=
CREATE_NEW_CONSOLE;
args-&
gt;startupInfo-&
gt;dwFlags &
amp;=
~
STARTF_USESTDHANDLES;
args-&
gt;startupInfo-&
gt;dwFlags |=
STARTF_USEFILLATTRIBUTE;
args-&
gt;startupInfo-&
gt;dwFillAttribute =
BACKGROUND_BLUE |
FOREGROUND_RED
|
FOREGROUND_INTENSITY;
}
);
process.start("C:
\\
Windows
\\
System32
\\
cmd.exe"
, QStringList() &
lt;&
lt; "/k"
&
lt;&
lt; "title"
&
lt;&
lt; "The Child Process"
);
See Also▲
enum QProcess::ExitStatus▲
This enum describes the different exit statuses of QProcess.
Constant |
Value |
Description |
---|---|---|
QProcess::NormalExit |
0 |
The process exited normally. |
QProcess::CrashExit |
1 |
The process crashed. |
See Also▲
See also exitStatus()
[since 5.2] enum QProcess::InputChannelMode▲
This enum describes the process input channel modes of QProcess. Pass one of these values to setInputChannelMode() to set the current write channel mode.
Constant |
Value |
Description |
---|---|---|
QProcess::ManagedInputChannel |
0 |
QProcess manages the input of the running process. This is the default input channel mode of QProcess. |
QProcess::ForwardedInputChannel |
1 |
QProcess forwards the input of the main process onto the running process. The child process reads its standard input from the same source as the main process. Note that the main process must not try to read its standard input while the child process is running. |
This enum was introduced or modified in Qt 5.2.
See Also▲
See also setInputChannelMode()
enum QProcess::ProcessChannel▲
This enum describes the process channels used by the running process. Pass one of these values to setReadChannel() to set the current read channel of QProcess.
Constant |
Value |
Description |
---|---|---|
QProcess::StandardOutput |
0 |
The standard output (stdout) of the running process. |
QProcess::StandardError |
1 |
The standard error (stderr) of the running process. |
See Also▲
See also setReadChannel()
enum QProcess::ProcessChannelMode▲
This enum describes the process output channel modes of QProcess. Pass one of these values to setProcessChannelMode() to set the current read channel mode.
Constant |
Value |
Description |
---|---|---|
QProcess::SeparateChannels |
0 |
QProcess manages the output of the running process, keeping standard output and standard error data in separate internal buffers. You can select the QProcess's current read channel by calling setReadChannel(). This is the default channel mode of QProcess. |
QProcess::MergedChannels |
1 |
QProcess merges the output of the running process into the standard output channel (stdout). The standard error channel (stderr) will not receive any data. The standard output and standard error data of the running process are interleaved. For detached processes, the merged output of the running process is forwarded onto the main process. |
QProcess::ForwardedChannels |
2 |
QProcess forwards the output of the running process onto the main process. Anything the child process writes to its standard output and standard error will be written to the standard output and standard error of the main process. |
QProcess::ForwardedErrorChannel |
4 |
QProcess manages the standard output of the running process, but forwards its standard error onto the main process. This reflects the typical use of command line tools as filters, where the standard output is redirected to another process or a file, while standard error is printed to the console for diagnostic purposes. (This value was introduced in Qt 5.2.) |
QProcess::ForwardedOutputChannel |
3 |
Complementary to ForwardedErrorChannel. (This value was introduced in Qt 5.2.) |
Windows intentionally suppresses output from GUI-only applications to inherited consoles. This does not apply to output redirected to files or pipes. To forward the output of GUI-only applications on the console nonetheless, you must use SeparateChannels and do the forwarding yourself by reading the output and writing it to the appropriate output channels.
See Also▲
See also setProcessChannelMode()
enum QProcess::ProcessError▲
This enum describes the different types of errors that are reported by QProcess.
Constant |
Value |
Description |
---|---|---|
QProcess::FailedToStart |
0 |
The process failed to start. Either the invoked program is missing, or you may have insufficient permissions or resources to invoke the program. |
QProcess::Crashed |
1 |
The process crashed some time after starting successfully. |
QProcess::Timedout |
2 |
The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again. |
QProcess::WriteError |
4 |
An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel. |
QProcess::ReadError |
3 |
An error occurred when attempting to read from the process. For example, the process may not be running. |
QProcess::UnknownError |
5 |
An unknown error occurred. This is the default return value of error(). |
See Also▲
See also error()
enum QProcess::ProcessState▲
This enum describes the different states of QProcess.
Constant |
Value |
Description |
---|---|---|
QProcess::NotRunning |
0 |
The process is not running. |
QProcess::Starting |
1 |
The process is starting, but the program has not yet been invoked. |
QProcess::Running |
2 |
The process is running and is ready for reading and writing. |
See Also▲
See also state()
Member Function Documentation▲
[explicit] QProcess::QProcess(QObject *parent = nullptr)▲
Constructs a QProcess object with the given parent.
[virtual] QProcess::~QProcess()▲
Destructs the QProcess object, i.e., killing the process.
Note that this function will not return until the process is terminated.
[since 5.0] QStringList QProcess::arguments() const▲
Returns the command line arguments the process was last started with.
This function was introduced in Qt 5.0.
See Also▲
See also setArguments(), start()
[override virtual] qint64 QProcess::bytesToWrite() const▲
Reimplements: QIODevice::bytesToWrite() const.
[since 6.0] std::function<void ()> QProcess::childProcessModifier() const▲
Returns the modifier function previously set by calling setChildProcessModifier().
This function is only available on Unix platforms.
This function was introduced in Qt 6.0.
See Also▲
See also setChildProcessModifier()
[override virtual] void QProcess::close()▲
Reimplements: QIODevice::close().
Closes all communication with the process and kills it. After calling this function, QProcess will no longer emit readyRead(), and data can no longer be read or written.
void QProcess::closeReadChannel(QProcess::ProcessChannel channel)▲
Closes the read channel channel. After calling this function, QProcess will no longer receive data on the channel. Any data that has already been received is still available for reading.
Call this function to save memory, if you are not interested in the output of the process.
See Also▲
See also closeWriteChannel(), setReadChannel()
void QProcess::closeWriteChannel()▲
Schedules the write channel of QProcess to be closed. The channel will close once all data has been written to the process. After calling this function, any attempts to write to the process will fail.
Closing the write channel is necessary for programs that read input data until the channel has been closed. For example, the program "more" is used to display text data in a console on both Unix and Windows. But it will not display the text data until QProcess's write channel has been closed. Example:
QProcess more;
more.start("more"
);
more.write("Text to display"
);
more.closeWriteChannel();
// QProcess will emit readyRead() once "more" starts printing
The write channel is implicitly opened when start() is called.
See Also▲
See also closeReadChannel()
[since 5.7] QProcess::CreateProcessArgumentModifier QProcess::createProcessArgumentsModifier() const▲
Returns a previously set CreateProcess modifier function.
This function is available only on the Windows platform.
This function was introduced in Qt 5.7.
See Also▲
QProcess::ProcessError QProcess::error() const▲
[since 5.6] void QProcess::errorOccurred(QProcess::ProcessError error)▲
This signal is emitted when an error occurs with the process. The specified error describes the type of error that occurred.
This function was introduced in Qt 5.6.
[static] int QProcess::execute(const QString &program, const QStringList &arguments = {})▲
Starts the program program with the arguments arguments in a new process, waits for it to finish, and then returns the exit code of the process. Any data the new process writes to the console is forwarded to the calling process.
The environment and working directory are inherited from the calling process.
Argument handling is identical to the respective start() overload.
If the process cannot be started, -2 is returned. If the process crashes, -1 is returned. Otherwise, the process' exit code is returned.
See Also▲
See also start()
int QProcess::exitCode() const▲
Returns the exit code of the last process that finished.
This value is not valid unless exitStatus() returns NormalExit.
QProcess::ExitStatus QProcess::exitStatus() const▲
Returns the exit status of the last process that finished.
On Windows, if the process was terminated with TerminateProcess() from another application, this function will still return NormalExit unless the exit code is less than 0.
void QProcess::finished(int exitCode, QProcess::ExitStatus exitStatus = NormalExit)▲
This signal is emitted when the process finishes. exitCode is the exit code of the process (only valid for normal exits), and exitStatus is the exit status. After the process has finished, the buffers in QProcess are still intact. You can still read any data that the process may have written before it finished.
See Also▲
See also exitStatus()
[since 5.2] QProcess::InputChannelMode QProcess::inputChannelMode() const▲
Returns the channel mode of the QProcess standard input channel.
This function was introduced in Qt 5.2.
See Also▲
See also setInputChannelMode(), InputChannelMode
[override virtual] bool QProcess::isSequential() const▲
Reimplements: QIODevice::isSequential() const.
void QProcess::kill()▲
Kills the current process, causing it to exit immediately.
On Windows, kill() uses TerminateProcess, and on Unix and macOS, the SIGKILL signal is sent to the process.
See Also▲
See also terminate()
QString QProcess::nativeArguments() const▲
Returns the additional native command line arguments for the program.
This function is available only on the Windows platform.
See Also▲
See also setNativeArguments()
[static, since 5.2] QString QProcess::nullDevice()▲
The null device of the operating system.
The returned file path uses native directory separators.
This function was introduced in Qt 5.2.
See Also▲
[override virtual] bool QProcess::open(QIODeviceBase::OpenMode mode = ReadWrite)▲
Reimplements: QIODevice::open(QIODeviceBase::OpenMode mode).
Starts the program set by setProgram() with arguments set by setArguments(). The OpenMode is set to mode.
This method is an alias for start(), and exists only to fully implement the interface defined by QIODevice.
Returns true if the program has been started.
See Also▲
See also start(), setProgram(), setArguments()
QProcess::ProcessChannelMode QProcess::processChannelMode() const▲
Returns the channel mode of the QProcess standard output and standard error channels.
See Also▲
See also setProcessChannelMode(), ProcessChannelMode, setReadChannel()
QProcessEnvironment QProcess::processEnvironment() const▲
Returns the environment that QProcess will pass to its child process, or an empty object if no environment has been set using setEnvironment() or setProcessEnvironment(). If no environment has been set, the environment of the calling process will be used.
See Also▲
See also setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
[since 5.3] qint64 QProcess::processId() const▲
Returns the native process identifier for the running process, if available. If no process is currently running, 0 is returned.
This function was introduced in Qt 5.3.
[since 5.0] QString QProcess::program() const▲
Returns the program the process was last started with.
This function was introduced in Qt 5.0.
See Also▲
See also setProgram(), start()
QByteArray QProcess::readAllStandardError()▲
Regardless of the current read channel, this function returns all data available from the standard error of the process as a QByteArray.
See Also▲
See also readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
QByteArray QProcess::readAllStandardOutput()▲
Regardless of the current read channel, this function returns all data available from the standard output of the process as a QByteArray.
See Also▲
See also readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
QProcess::ProcessChannel QProcess::readChannel() const▲
[override virtual protected] qint64 QProcess::readData(char *data, qint64 maxlen)▲
Reimplements: QIODevice::readData(char *data, qint64 maxSize).
void QProcess::readyReadStandardError()▲
This signal is emitted when the process has made new data available through its standard error channel (stderr). It is emitted regardless of the current read channel.
This is a private signal. It can be used in signal connections but cannot be emitted by the user.
See Also▲
See also readAllStandardError(), readChannel()
void QProcess::readyReadStandardOutput()▲
This signal is emitted when the process has made new data available through its standard output channel (stdout). It is emitted regardless of the current read channel.
This is a private signal. It can be used in signal connections but cannot be emitted by the user.
See Also▲
See also readAllStandardOutput(), readChannel()
[since 5.1] void QProcess::setArguments(const QStringList &arguments)▲
Set the arguments to pass to the called program when starting the process. This function must be called before start().
This function was introduced in Qt 5.1.
See Also▲
See also start(), setProgram(), arguments()
[since 6.0] void QProcess::setChildProcessModifier(const std::function<void ()> &modifier)▲
Sets the modifier function for the child process, for Unix systems (including macOS; for Windows, see setCreateProcessArgumentsModifier()). The function contained by the modifier argument will be invoked in the child process after fork() is completed and QProcess has set up the standard file descriptors for the child process, but before execve(), inside start(). The modifier is useful to change certain properties of the child process, such as setting up additional file descriptors or closing others, changing the nice level, disconnecting from the controlling TTY, etc.
The following shows an example of setting up a child process to run without privileges:
void
runSandboxed(const
QString &
amp;name, const
QStringList &
amp;arguments)
{
QProcess proc;
proc.setChildProcessModifier([] {
// Drop all privileges in the child process, and enter
// a chroot jail.
::
setgroups(0
, nullptr
);
::
chroot("/run/safedir"
);
::
chdir("/"
);
::
setgid(safeGid);
::
setuid(safeUid);
::
umask(077
);
}
);
proc.start(name, arguments);
proc.waitForFinished();
}
If the modifier function needs to exit the process, remember to use _exit(), not exit().
In multithreaded applications, this function must be careful not to call any functions that may lock mutexes that may have been in use in other threads (in general, using only functions defined by POSIX as "async-signal-safe" is advised). Most of the Qt API is unsafe inside this callback, including qDebug(), and may lead to deadlocks.
This function was introduced in Qt 6.0.
See Also▲
See also childProcessModifier()
[since 5.7] void QProcess::setCreateProcessArgumentsModifier(QProcess::CreateProcessArgumentModifier modifier)▲
Sets the modifier for the CreateProcess Win32 API call. Pass QProcess::CreateProcessArgumentModifier() to remove a previously set one.
This function is available only on the Windows platform and requires C++11.
This function was introduced in Qt 5.7.
See Also▲
[since 5.2] void QProcess::setInputChannelMode(QProcess::InputChannelMode mode)▲
Sets the channel mode of the QProcess standard input channel to the mode specified. This mode will be used the next time start() is called.
This function was introduced in Qt 5.2.
See Also▲
See also inputChannelMode(), InputChannelMode
void QProcess::setNativeArguments(const QString &arguments)▲
This is an overloaded function.
Sets additional native command line arguments for the program.
On operating systems where the system API for passing command line arguments to a subprocess natively uses a single string, one can conceive command lines which cannot be passed via QProcess's portable list-based API. In such cases this function must be used to set a string which is appended to the string composed from the usual argument list, with a delimiting space.
This function is available only on the Windows platform.
See Also▲
See also nativeArguments()
void QProcess::setProcessChannelMode(QProcess::ProcessChannelMode mode)▲
Sets the channel mode of the QProcess standard output and standard error channels to the mode specified. This mode will be used the next time start() is called. For example:
QProcess builder;
builder.setProcessChannelMode(QProcess::
MergedChannels);
builder.start("make"
, QStringList() &
lt;&
lt; "-j2"
);
if
(!
builder.waitForFinished())
qDebug() &
lt;&
lt; "Make failed:"
&
lt;&
lt; builder.errorString();
else
qDebug() &
lt;&
lt; "Make output:"
&
lt;&
lt; builder.readAll();
See Also▲
See also processChannelMode(), ProcessChannelMode, setReadChannel()
void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)▲
Sets the environment that QProcess will pass to the child process.
For example, the following code adds the environment variable TMPDIR:
QProcess process;
QProcessEnvironment env =
QProcessEnvironment::
systemEnvironment();
env.insert("TMPDIR"
, "C:
\\
MyApp
\\
temp"
); // Add an environment variable
process.setProcessEnvironment(env);
process.start("myapp"
);
Note how, on Windows, environment variable names are case-insensitive.
See Also▲
See also processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
[protected] void QProcess::setProcessState(QProcess::ProcessState state)▲
[since 5.1] void QProcess::setProgram(const QString &program)▲
Set the program to use when starting the process. This function must be called before start().
If program is an absolute path, it specifies the exact executable that will be launched. Relative paths will be resolved in a platform-specific manner, which includes searching the PATH environment variable (see Finding the Executable for details).
This function was introduced in Qt 5.1.
See Also▲
See also start(), setArguments(), program(), QStandardPaths::findExecutable()
void QProcess::setReadChannel(QProcess::ProcessChannel channel)▲
Sets the current read channel of the QProcess to the given channel. The current input channel is used by the functions read(), readAll(), readLine(), and getChar(). It also determines which channel triggers QProcess to emit readyRead().
See Also▲
See also readChannel()
void QProcess::setStandardErrorFile(const QString &fileName, QIODeviceBase::OpenMode mode = Truncate)▲
Redirects the process' standard error to the file fileName. When the redirection is in place, the standard error read channel is closed: reading from it using read() will always fail, as will readAllStandardError(). The file will be appended to if mode is Append, otherwise, it will be truncated.
See setStandardOutputFile() for more information on how the file is opened.
Note: if setProcessChannelMode() was called with an argument of QProcess::MergedChannels, this function has no effect.
See Also▲
See also setStandardInputFile(), setStandardOutputFile(), setStandardOutputProcess()
void QProcess::setStandardInputFile(const QString &fileName)▲
Redirects the process' standard input to the file indicated by fileName. When an input redirection is in place, the QProcess object will be in read-only mode (calling write() will result in error).
To make the process read EOF right away, pass nullDevice() here. This is cleaner than using closeWriteChannel() before writing any data, because it can be set up prior to starting the process.
If the file fileName does not exist at the moment start() is called or is not readable, starting the process will fail.
Calling setStandardInputFile() after the process has started has no effect.
See Also▲
See also setStandardOutputFile(), setStandardErrorFile(), setStandardOutputProcess()
void QProcess::setStandardOutputFile(const QString &fileName, QIODeviceBase::OpenMode mode = Truncate)▲
Redirects the process' standard output to the file fileName. When the redirection is in place, the standard output read channel is closed: reading from it using read() will always fail, as will readAllStandardOutput().
To discard all standard output from the process, pass nullDevice() here. This is more efficient than simply never reading the standard output, as no QProcess buffers are filled.
If the file fileName doesn't exist at the moment start() is called, it will be created. If it cannot be created, the starting will fail.
If the file exists and mode is QIODevice::Truncate, the file will be truncated. Otherwise (if mode is QIODevice::Append), the file will be appended to.
Calling setStandardOutputFile() after the process has started has no effect.
See Also▲
See also setStandardInputFile(), setStandardErrorFile(), setStandardOutputProcess()
void QProcess::setStandardOutputProcess(QProcess *destination)▲
Pipes the standard output stream of this process to the destination process' standard input.
The following shell command:
command1 |
command2
Can be accomplished with QProcess with the following code:
QProcess process1;
QProcess process2;
process1.setStandardOutputProcess(&
amp;process2);
process1.start("command1"
);
process2.start("command2"
);
void QProcess::setWorkingDirectory(const QString &dir)▲
Sets the working directory to dir. QProcess will start the process in this directory. The default behavior is to start the process in the working directory of the calling process.
On QNX, this may cause all application threads to temporarily freeze.
See Also▲
See also workingDirectory(), start()
[static, since 5.15] QStringList QProcess::splitCommand(QStringView command)▲
Splits the string command into a list of tokens, and returns the list.
Tokens with spaces can be surrounded by double quotes; three consecutive double quotes represent the quote character itself.
This function was introduced in Qt 5.15.
void QProcess::start(const QString &program, const QStringList &arguments = {}, QIODeviceBase::OpenMode mode = ReadWrite)▲
Starts the given program in a new process, passing the command line arguments in arguments. See setProgram() for information about how QProcess searches for the executable to be run.
The QProcess object will immediately enter the Starting state. If the process starts successfully, QProcess will emit started(); otherwise, errorOccurred() will be emitted.
Processes are started asynchronously, which means the started() and errorOccurred() signals may be delayed. Call waitForStarted() to make sure the process has started (or has failed to start) and those signals have been emitted.
No further splitting of the arguments is performed.
Windows: The arguments are quoted and joined into a command line that is compatible with the CommandLineToArgvW() Windows function. For programs that have different command line quoting requirements, you need to use setNativeArguments(). One notable program that does not follow the CommandLineToArgvW() rules is cmd.exe and, by consequence, all batch scripts.
The OpenMode is set to mode.
If the QProcess object is already running a process, a warning may be printed at the console, and the existing process will continue running unaffected.
See Also▲
See also processId(), started(), waitForStarted(), setNativeArguments()
[since 5.1] void QProcess::start(QIODeviceBase::OpenMode mode = ReadWrite)▲
This is an overloaded function.
Starts the program set by setProgram() with arguments set by setArguments(). The OpenMode is set to mode.
This function was introduced in Qt 5.1.
See Also▲
See also open(), setProgram(), setArguments()
[since 6.0] void QProcess::startCommand(const QString &command, QIODeviceBase::OpenMode mode = ReadWrite)▲
Starts the command command in a new process. The OpenMode is set to mode.
command is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces. For example:
QProcess process;
process.startCommand("del /s *.txt"
);
// same as process.start("del", QStringList() << "/s" << "*.txt");
...
Arguments containing spaces must be quoted to be correctly supplied to the new process. For example:
QProcess process;
process.startCommand("dir
\"
My Documents
\"
"
);
Literal quotes in the command string are represented by triple quotes. For example:
QProcess process;
process.startCommand("dir
\"
Epic 12
\"\"\"
Singles
\"
"
);
After the command string has been split and unquoted, this function behaves like start().
On operating systems where the system API for passing command line arguments to a subprocess natively uses a single string (Windows), one can conceive command lines which cannot be passed via QProcess's portable list-based API. In these rare cases you need to use setProgram() and setNativeArguments() instead of this function.
This function was introduced in Qt 6.0.
See Also▲
See also splitCommand(), start()
[since 5.10] bool QProcess::startDetached(qint64 *pid = nullptr)▲
Starts the program set by setProgram() with arguments set by setArguments() in a new process, and detaches from it. Returns true on success; otherwise returns false. If the calling process exits, the detached process will continue to run unaffected.
Unix: The started process will run in its own session and act like a daemon.
The process will be started in the directory set by setWorkingDirectory(). If workingDirectory() is empty, the working directory is inherited from the calling process.
On QNX, this may cause all application threads to temporarily freeze.
If the function is successful then *pid is set to the process identifier of the started process; otherwise, it's set to -1. Note that the child process may exit and the PID may become invalid without notice. Furthermore, after the child process exits, the same PID may be recycled and used by a completely different process. User code should be careful when using this variable, especially if one intends to forcibly terminate the process by operating system means.
Only the following property setters are supported by startDetached():
All other properties of the QProcess object are ignored.
The called process inherits the console window of the calling process. To suppress console output, redirect standard/error output to QProcess::nullDevice().
This function was introduced in Qt 5.10.
See Also▲
See also start(), startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid)
[static] bool QProcess::startDetached(const QString &program, const QStringList &arguments = {}, const QString &workingDirectory = QString(), qint64 *pid = nullptr)▲
This function overloads startDetached().
Starts the program program with the arguments arguments in a new process, and detaches from it. Returns true on success; otherwise returns false. If the calling process exits, the detached process will continue to run unaffected.
Argument handling is identical to the respective start() overload.
The process will be started in the directory workingDirectory. If workingDirectory is empty, the working directory is inherited from the calling process.
If the function is successful then *pid is set to the process identifier of the started process.
See Also▲
See also start()
void QProcess::started()▲
This signal is emitted by QProcess when the process has started, and state() returns Running.
This is a private signal. It can be used in signal connections but cannot be emitted by the user.
QProcess::ProcessState QProcess::state() const▲
void QProcess::stateChanged(QProcess::ProcessState newState)▲
This signal is emitted whenever the state of QProcess changes. The newState argument is the state QProcess changed to.
This is a private signal. It can be used in signal connections but cannot be emitted by the user.
[static] QStringList QProcess::systemEnvironment()▲
Returns the environment of the calling process as a list of key=value pairs. Example:
QStringList environment =
QProcess::
systemEnvironment();
// environment = {"PATH=/usr/bin:/usr/local/bin",
// "USER=greg", "HOME=/home/greg"}
This function does not cache the system environment. Therefore, it's possible to obtain an updated version of the environment if low-level C library functions like setenv or putenv have been called.
However, note that repeated calls to this function will recreate the list of environment variables, which is a non-trivial operation.
For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
See Also▲
See also QProcessEnvironment::systemEnvironment(), setProcessEnvironment()
void QProcess::terminate()▲
Attempts to terminate the process.
The process may not exit as a result of calling this function (it is given the chance to prompt the user for any unsaved files, etc).
On Windows, terminate() posts a WM_CLOSE message to all top-level windows of the process and then to the main thread of the process itself. On Unix and macOS the SIGTERM signal is sent.
Console applications on Windows that do not run an event loop, or whose event loop does not handle the WM_CLOSE message, can only be terminated by calling kill().
See Also▲
See also kill()
[override virtual] bool QProcess::waitForBytesWritten(int msecs = 30000)▲
Reimplements: QIODevice::waitForBytesWritten(int msecs).
bool QProcess::waitForFinished(int msecs = 30000)▲
Blocks until the process has finished and the finished() signal has been emitted, or until msecs milliseconds have passed.
Returns true if the process finished; otherwise returns false (if the operation timed out, if an error occurred, or if this QProcess is already finished).
This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.
Calling this function from the main (GUI) thread might cause your user interface to freeze.
If msecs is -1, this function will not time out.
See Also▲
See also finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
[override virtual] bool QProcess::waitForReadyRead(int msecs = 30000)▲
Reimplements: QIODevice::waitForReadyRead(int msecs).
bool QProcess::waitForStarted(int msecs = 30000)▲
Blocks until the process has started and the started() signal has been emitted, or until msecs milliseconds have passed.
Returns true if the process was started successfully; otherwise returns false (if the operation timed out or if an error occurred).
This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.
Calling this function from the main (GUI) thread might cause your user interface to freeze.
If msecs is -1, this function will not time out.
On some UNIX operating systems, this function may return true but the process may later report a QProcess::FailedToStart error.
See Also▲
See also started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
QString QProcess::workingDirectory() const▲
If QProcess has been assigned a working directory, this function returns the working directory that the QProcess will enter before the program has started. Otherwise, (i.e., no directory has been assigned,) an empty string is returned, and QProcess will use the application's current working directory instead.
See Also▲
See also setWorkingDirectory()
Obsolete Members for QProcess▲
The following members of class QProcess are deprecated. We strongly advise against using them in new code.
Obsolete Member Function Documentation▲
QStringList QProcess::environment() const▲
This function is deprecated. We strongly advise against using it in new code.
Returns the environment that QProcess will pass to its child process, or an empty QStringList if no environment has been set using setEnvironment(). If no environment has been set, the environment of the calling process will be used.
See Also▲
See also processEnvironment(), setEnvironment(), systemEnvironment()
void QProcess::setEnvironment(const QStringList &environment)▲
This function is deprecated. We strongly advise against using it in new code.
Sets the environment that QProcess will pass to the child process. The parameter environment is a list of key=value pairs.
For example, the following code adds the environment variable TMPDIR:
QProcess process;
QStringList env =
QProcess::
systemEnvironment();
env &
lt;&
lt; "TMPDIR=C:
\\
MyApp
\\
temp"
; // Add an environment variable
process.setEnvironment(env);
process.start("myapp"
);
This function is less efficient than the setProcessEnvironment() function.
See Also▲
See also environment(), setProcessEnvironment(), systemEnvironment()