QProcess Class

The QProcess class is used to start external programs and to communicate with them. More...

Header: #include <QProcess>
qmake: QT += core
Inherits: QIODevice

Note: All functions in this class are reentrant.

Public Types

struct CreateProcessArguments
typedef CreateProcessArgumentModifier
enum ExitStatus { NormalExit, CrashExit }
enum InputChannelMode { ManagedInputChannel, ForwardedInputChannel }
enum ProcessChannel { StandardOutput, StandardError }
enum ProcessChannelMode { SeparateChannels, MergedChannels, ForwardedChannels, ForwardedErrorChannel, ForwardedOutputChannel }
enum ProcessError { FailedToStart, Crashed, Timedout, WriteError, ReadError, UnknownError }
enum ProcessState { NotRunning, Starting, Running }
typedef Q_PID

Macros

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 << "-style" << "fusion";

     QProcess *myProcess = new QProcess(parent);
     myProcess->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.

Note: QProcess is not supported on VxWorks, iOS, tvOS, watchOS, or the Universal Windows Platform.

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.

Note: 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() << "-c");
     if (!gzip.waitForStarted())
         return false;

     gzip.write("Qt rocks!");
     gzip.closeWriteChannel();

     if (!gzip.waitForFinished())
         return false;

     QByteArray result = gzip.readAll();

Notes for Windows Users

Some Windows commands (for example, dir) are not provided by separate applications, but by the command interpreter itself. If you attempt to use QProcess to execute these commands directly, it won't work. One possible solution is to execute the command interpreter itself (cmd.exe on some Windows systems), and ask the interpreter to execute the desired command.

See also QBuffer, QFile, and QTcpSocket.

Member Type Documentation

typedef QProcess::CreateProcessArgumentModifier

Note: 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->flags |= CREATE_NEW_CONSOLE;
         args->startupInfo->dwFlags &= ~STARTF_USESTDHANDLES;
         args->startupInfo->dwFlags |= STARTF_USEFILLATTRIBUTE;
         args->startupInfo->dwFillAttribute = BACKGROUND_BLUE | FOREGROUND_RED
                                            | FOREGROUND_INTENSITY;
     });
     process.start("C:\\Windows\\System32\\cmd.exe", QStringList() << "/k" << "title" << "The Child Process");

See also QProcess::CreateProcessArguments and setCreateProcessArgumentsModifier().

enum QProcess::ExitStatus

This enum describes the different exit statuses of QProcess.

ConstantValueDescription
QProcess::NormalExit0The process exited normally.
QProcess::CrashExit1The process crashed.

See also exitStatus().

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.

ConstantValueDescription
QProcess::ManagedInputChannel0QProcess manages the input of the running process. This is the default input channel mode of QProcess.
QProcess::ForwardedInputChannel1QProcess 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 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.

ConstantValueDescription
QProcess::StandardOutput0The standard output (stdout) of the running process.
QProcess::StandardError1The standard error (stderr) of the running process.

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.

ConstantValueDescription
QProcess::SeparateChannels0QProcess 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::MergedChannels1QProcess 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.
QProcess::ForwardedChannels2QProcess 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::ForwardedErrorChannel4QProcess 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::ForwardedOutputChannel3Complementary to ForwardedErrorChannel. (This value was introduced in Qt 5.2.)

Note: 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 setProcessChannelMode().

enum QProcess::ProcessError

This enum describes the different types of errors that are reported by QProcess.

ConstantValueDescription
QProcess::FailedToStart0The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.
QProcess::Crashed1The process crashed some time after starting successfully.
QProcess::Timedout2The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.
QProcess::WriteError4An 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::ReadError3An error occurred when attempting to read from the process. For example, the process may not be running.
QProcess::UnknownError5An unknown error occurred. This is the default return value of error().

See also error().

enum QProcess::ProcessState

This enum describes the different states of QProcess.

ConstantValueDescription
QProcess::NotRunning0The process is not running.
QProcess::Starting1The process is starting, but the program has not yet been invoked.
QProcess::Running2The process is running and is ready for reading and writing.

See also state().

Related Non-Members

typedef Q_PID

Typedef for the identifiers used to represent processes on the underlying platform. On Unix, this corresponds to qint64; on Windows, it corresponds to _PROCESS_INFORMATION*.

See also QProcess::pid().

Macro Documentation

QT_NO_PROCESS_COMBINED_ARGUMENT_START

Disables the QProcess::start() overload taking a single string. In most cases where it is used, the user intends for the first argument to be treated atomically as per the other overload.

This function was introduced in Qt 5.6.

See also QProcess::start(const QString &command, QIODevice::OpenMode mode).