6.0.0-rc4Source

QProcess Class

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

Header#include <QProcess>
CMaketarget_link_libraries(app PRIVATE Nt::Core)
ModuleNt Core C++ Classes
InheritsQIODevice

List of all members, including inherited members

Public Types

Public Functions

QProcess(QObject *parent = nullptr)
~QProcess()
voidstart(const QString &program, const QStringList &arguments = QStringList(), OpenMode mode = ReadWrite)
voidstart(OpenMode mode = ReadWrite)
voidstartCommand(const QString &command, OpenMode mode = ReadWrite)
boolstartDetached(qint64 *pid = nullptr)
QStringprogram() const
voidsetProgram(const QString &program)
QStringListarguments() const
voidsetArguments(const QStringList &arguments)
QStringworkingDirectory() const
voidsetWorkingDirectory(const QString &dir)
QProcessEnvironmentprocessEnvironment() const
voidsetProcessEnvironment(const QProcessEnvironment &environment)
ProcessChannelModeprocessChannelMode() const
voidsetProcessChannelMode(ProcessChannelMode mode)
InputChannelModeinputChannelMode() const
voidsetInputChannelMode(InputChannelMode mode)
ProcessChannelreadChannel() const
voidsetReadChannel(ProcessChannel channel)
voidcloseReadChannel(ProcessChannel channel)
voidcloseWriteChannel()
voidsetStandardInputFile(const QString &fileName)
voidsetStandardOutputFile(const QString &fileName, OpenMode mode = Truncate)
voidsetStandardErrorFile(const QString &fileName, OpenMode mode = Truncate)
voidsetStandardOutputProcess(QProcess *destination)
voidsetChildProcessModifier(const std::function<void()> &modifier)
ProcessErrorerror() const
ProcessStatestate() const
qint64processId() const
intexitCode() const
ExitStatusexitStatus() const
boolwaitForStarted(int msecs = 30000)
boolwaitForFinished(int msecs = 30000)
QByteArrayreadAllStandardOutput()
QByteArrayreadAllStandardError()

Reimplemented Public Functions

boolopen(OpenMode mode = ReadWrite)
boolwaitForReadyRead(int msecs = 30000)
boolwaitForBytesWritten(int msecs = 30000)
qint64bytesAvailable() const
qint64bytesToWrite() const
boolcanReadLine() const
voidclose()

Public Slots

voidterminate()
voidkill()

Signals

Static Public Members

boolstartDetached(const QString &program, const QStringList &arguments = QStringList(), const QString &workingDirectory = QString(), qint64 *pid = nullptr)
intexecute(const QString &program, const QStringList &arguments = QStringList())
QStringListsplitCommand(QStringView command)
QStringListsystemEnvironment()
QStringnullDevice()

Reimplemented Protected Functions

qint64readData(char *data, qint64 maxSize)
qint64writeData(const char *data, qint64 maxSize)
voidtimerEvent(QTimerEvent *event)

Detailed Description

QProcess runs a program in a child process and exchanges data with it through pipes. Start a program with start(); the process runs asynchronously and QProcess reports progress through signals, driven by the event loop. Output arrives on readyReadStandardOutput() and readyReadStandardError(); write input with write() and call closeWriteChannel() when done. The process is complete once finished() has been emitted.

QProcess process;
QObject::connect(&process, &QProcess::finished, [&](int code, QProcess::ExitStatus status) {
    qDebug() << "exit code" << code << process.readAllStandardOutput();
});
process.start("sort", QStringList());
process.write("b\na\n");
process.closeWriteChannel();

The waitFor...() functions block instead, without running the event loop; they still emit signals and move data while they wait.

The program is started with fork() and execve(). A program name without a slash is searched in PATH (the child's PATH when an environment was set). A failure to execute the program, or to change to the working directory, is reported through a close-on-exec pipe: state() goes back to NotRunning and errorOccurred() is emitted with FailedToStart. The end of the child is detected through a pidfd where the kernel provides one, and by polling waitpid() otherwise; the child is always reaped and QProcess installs no SIGCHLD handler, so it does not interfere with the application's own. The application must not reap children it did not start itself with waitpid(-1).

Destroying a QProcess that is still running kills the child, after a warning, and waits for it.

See also QProcessEnvironment and QIODevice.

Differences from Qt

The platform is POSIX only. The write buffer is unbounded and there is no setReadBufferSize(). A crashed child reports an exitCode() of 0 and exitStatus() CrashExit. There is no deprecated setEnvironment() or environment(), no UnixProcessParameters and no setCreateProcessArgumentsModifier(). The poller of an unsupported kernel adds up to 10 ms of delay in detecting the end of a child. The finished() signal has no overload taking only the exit code.

The class is not built for Zephyr, where QT_NO_PROCESS is defined instead. See Nt on Zephyr.

Member Type Documentation

enum QProcess::ExitStatus

ConstantDescription
QProcess::NormalExitThe process exited normally.
QProcess::CrashExitThe process crashed, that is, it was terminated by a signal.

enum QProcess::InputChannelMode

ConstantDescription
QProcess::ManagedInputChannelQProcess manages the input of the running process.
QProcess::ForwardedInputChannelThe child process reads the standard input of the parent process.

enum QProcess::ProcessChannel

ConstantDescription
QProcess::StandardOutputThe standard output (stdout) of the running process.
QProcess::StandardErrorThe standard error (stderr) of the running process.

enum QProcess::ProcessChannelMode

ConstantDescription
QProcess::SeparateChannelsQProcess manages the output of the running process, keeping standard output and standard error data in separate internal buffers.
QProcess::MergedChannelsQProcess merges the output of the running process into the standard output channel.
QProcess::ForwardedChannelsQProcess forwards the output of the running process onto the main process: the child writes to the parent's stdout and stderr.
QProcess::ForwardedOutputChannelOnly the standard output of the child is forwarded; standard error is managed.
QProcess::ForwardedErrorChannelOnly the standard error of the child is forwarded; standard output is managed.

enum QProcess::ProcessError

This enum describes the errors that can occur.

ConstantDescription
QProcess::FailedToStartThe process failed to start, for example because the program does not exist or the process lacks permission to run it.
QProcess::CrashedThe process crashed some time after starting successfully.
QProcess::TimedoutThe last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.
QProcess::WriteErrorAn error occurred when attempting to write to the process.
QProcess::ReadErrorAn error occurred when attempting to read from the process.
QProcess::UnknownErrorAn unknown error occurred.

enum QProcess::ProcessState

ConstantDescription
QProcess::NotRunningThe process is not running.
QProcess::StartingThe process is starting, but the program has not yet been invoked.
QProcess::RunningThe process is running and is ready for reading and writing.

Member Function Documentation

[explicit] QProcess::QProcess(QObject *parent = nullptr)

Constructs a QProcess object with the given parent. The process is not running.

[override] QProcess::~QProcess()

Destroys the QProcess object. If the process is still running, a warning is printed, the process is killed and the destructor waits for it to finish.

QStringList QProcess::arguments() const

Returns the arguments set with setArguments() or start().

See also setArguments().

[override] qint64 QProcess::bytesAvailable() const

Reimplements QIODevice::bytesAvailable().

Returns the number of bytes available for reading on the current read channel.

See also setReadChannel() and readAllStandardOutput().

[override] qint64 QProcess::bytesToWrite() const

Reimplements QIODevice::bytesToWrite().

Returns the number of bytes written to the process that have not been passed to the operating system yet.

See also write() and waitForBytesWritten().

[override] bool QProcess::canReadLine() const

Reimplements QIODevice::canReadLine().

Returns true if a complete line can be read from the current read channel; otherwise returns false.

See also readLine().

[override] void QProcess::close()

Reimplements QIODevice::close().

Closes the read and write channels, terminates the process if it is running (killing it if it does not finish within five seconds) and sets the open mode to NotOpen. Emits aboutToClose() first.

void QProcess::closeReadChannel(ProcessChannel channel)

Closes the read channel channel. The process may receive SIGPIPE when it next writes to it. Data that has already been buffered stays readable.

See also closeWriteChannel().

void QProcess::closeWriteChannel()

Schedules the write channel to be closed. It closes once all data written so far has reached the process, which then sees end-of-file on its standard input. The device is no longer writable.

See also write() and closeReadChannel().

ProcessError QProcess::error() const

Returns the type of error that occurred last, or UnknownError if none has occurred since the last start.

See also errorString() and errorOccurred().

[signal] void QProcess::errorOccurred(QProcess::ProcessError error)

This signal is emitted when an error occurs with the process. The error parameter describes the type of error that occurred. It is not emitted for Timedout.

See also error() and errorString().

[static] int QProcess::execute(const QString &program, const QStringList &arguments = QStringList())

Starts program with arguments in a new process, forwarding its output channels, and waits for it to finish. Returns the exit code of the process, -2 if the process could not be started and -1 if it crashed.

See also start() and waitForFinished().

int QProcess::exitCode() const

Returns the exit code of the last process that finished. It is only meaningful if exitStatus() is NormalExit.

See also exitStatus() and finished().

ExitStatus QProcess::exitStatus() const

Returns the exit status of the last process that finished: CrashExit if it was terminated by a signal.

See also exitCode() and finished().

[signal] 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 exitStatus(), exitCode() and errorOccurred().

InputChannelMode QProcess::inputChannelMode() const

Returns the channel mode of the standard input channel.

See also setInputChannelMode().

[slot] void QProcess::kill()

Kills the process, causing it to exit immediately: it sends SIGKILL. The process then finishes with the CrashExit status. Does nothing if no process is running.

See also terminate().

[static] QString QProcess::nullDevice()

Returns the path of the system's null device, /dev/null.

See also setStandardOutputFile().

[override] bool QProcess::open(OpenMode mode = ReadWrite)

Reimplements QIODevice::open().

Opens the device in mode and starts the program set with setProgram(), like start(). Returns true if a start was attempted; returns false and does nothing if the process is already running or no program was set.

See also start().

ProcessChannelMode QProcess::processChannelMode() const

Returns the channel mode of the standard output and standard error channels.

See also setProcessChannelMode().

QProcessEnvironment QProcess::processEnvironment() const

Returns the environment set with setProcessEnvironment(). If none was set, the result inherits from the parent (see QProcessEnvironment::inheritsFromParent()).

See also setProcessEnvironment() and systemEnvironment().

qint64 QProcess::processId() const

Returns the native process identifier of the running process, or 0 if no process is running.

QString QProcess::program() const

Returns the program set with setProgram() or start().

See also setProgram().

QByteArray QProcess::readAllStandardError()

Reads and returns all data buffered from the standard error channel, whatever the current read channel is.

See also readAllStandardOutput() and readyReadStandardError().

QByteArray QProcess::readAllStandardOutput()

Reads and returns all data buffered from the standard output channel, whatever the current read channel is.

See also readAllStandardError() and readyReadStandardOutput().

ProcessChannel QProcess::readChannel() const

Returns the current read channel, the one that read(), readAll() and readLine() read from and that triggers readyRead().

See also setReadChannel().

[override, protected] qint64 QProcess::readData(char *data, qint64 maxSize)

Reimplements QIODevice::readData().

[signal] 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.

See also readAllStandardError() and readChannel().

[signal] 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.

See also readAllStandardOutput() and readChannel().

void QProcess::setArguments(const QStringList &arguments)

Sets the arguments passed to the program at the next start. This has no effect on a running process.

See also arguments() and setProgram().

void QProcess::setChildProcessModifier(const std::function<void()> &modifier)

Sets modifier to be called in the child process after it has been forked and its channels set up, just before the program is executed. It runs in the child of a possibly multi-threaded process, so it may only call async-signal-safe functions.

See also start().

void QProcess::setInputChannelMode(InputChannelMode mode)

Sets the channel mode of the standard input channel to mode. It takes effect at the next start.

See also inputChannelMode().

void QProcess::setProcessChannelMode(ProcessChannelMode mode)

Sets the channel mode of the standard output and standard error channels to mode. It takes effect at the next start.

See also processChannelMode() and setReadChannel().

void QProcess::setProcessEnvironment(const QProcessEnvironment &environment)

Sets the environment passed to the next process to environment. If environment inherits from the parent, which is the default, the child gets the parent's environment.

See also processEnvironment() and QProcessEnvironment::systemEnvironment().

void QProcess::setProgram(const QString &program)

Sets the program to run. It is used by the next start() without a program argument. This has no effect on a running process.

See also program() and setArguments().

void QProcess::setReadChannel(ProcessChannel channel)

Sets the current read channel to channel.

See also readChannel() and readAllStandardOutput().

void QProcess::setStandardErrorFile(const QString &fileName, OpenMode mode = Truncate)

Redirects the standard error of the next process to the file fileName, created if it does not exist. With mode Append the file is appended to; otherwise it is truncated. It has no effect with the MergedChannels mode.

See also setStandardOutputFile().

void QProcess::setStandardInputFile(const QString &fileName)

Redirects the standard input of the next process to read from the file fileName instead of a pipe.

See also setStandardOutputFile() and setInputChannelMode().

void QProcess::setStandardOutputFile(const QString &fileName, OpenMode mode = Truncate)

Redirects the standard output of the next process to the file fileName, created if it does not exist. With mode Append the file is appended to; otherwise it is truncated. Pass nullDevice() to discard output. An empty fileName cancels the redirection.

If the process channel mode is MergedChannels, standard error goes to the file as well.

See also setStandardErrorFile() and setStandardInputFile().

void QProcess::setStandardOutputProcess(QProcess *destination)

Pipes the standard output of this process directly into the standard input of destination, like the shell's |. Either process can be started first; the pipe exists from the first start. Pass nullptr to undo it. The standard output of this process is then no longer readable.

See also setStandardOutputFile().

void QProcess::setWorkingDirectory(const QString &dir)

Sets the working directory of the next process to dir. If the directory cannot be entered, the process fails to start.

See also workingDirectory().

[static] QStringList QProcess::splitCommand(QStringView command)

Splits command into tokens separated by white space and returns them. A token that contains white space can be surrounded by double quotes; three consecutive double quotes stand for a quote character itself.

See also startCommand().

void QProcess::start(const QString &program, const QStringList &arguments = QStringList(), OpenMode mode = ReadWrite)

Starts the given program in a new process with arguments, if no process is running, and opens the device in mode. The function returns immediately; the process is started when the event loop runs, or when a waitFor...() function is called. A failure to start is reported through errorOccurred().

The program name is looked up in PATH if it has no slash. Arguments are passed as given, without shell interpretation.

See also startCommand(), setProgram() and waitForStarted().

void QProcess::start(OpenMode mode = ReadWrite)

This is an overloaded function.

Starts the program set by setProgram() with the arguments set by setArguments(), opening the device in mode.

See also open().

void QProcess::startCommand(const QString &command, OpenMode mode = ReadWrite)

Starts the command command in a new process and opens the device in mode. The command is split with splitCommand(): the first token is the program and the others are its arguments. Nothing is interpreted by a shell.

See also splitCommand() and start().

bool QProcess::startDetached(qint64 *pid = nullptr)

Starts the program in a new process that is detached from this one and continues to run after the application exits, using the program, arguments, working directory and environment set on this object. The process becomes a session leader, its standard input is /dev/null and its output goes to the null device, unless a redirection or a forwarded channel mode says otherwise. Returns true on success; if pid is not nullptr, it receives the process identifier. The QProcess object stays in the NotRunning state.

See also start().

[static] bool QProcess::startDetached(const QString &program, const QStringList &arguments = QStringList(), const QString &workingDirectory = QString(), qint64 *pid = nullptr)

This is an overloaded function.

Starts program with arguments in the working directory workingDirectory as a detached process. Returns true on success; if pid is not nullptr, it receives the process identifier.

[signal] void QProcess::started()

This signal is emitted by QProcess when the process has started and state() returns Running.

See also errorOccurred() and stateChanged().

ProcessState QProcess::state() const

Returns the current state of the process.

See also stateChanged() and error().

[signal] 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.

See also state().

[static] QStringList QProcess::systemEnvironment()

Returns the environment of the calling process as a list of NAME=value strings.

See also QProcessEnvironment::systemEnvironment().

[slot] void QProcess::terminate()

Terminates the process, giving it the chance to clean up: it sends SIGTERM. Does nothing if no process is running.

See also kill().

[override, protected] void QProcess::timerEvent(QTimerEvent *event)

Reimplements QIODevice::timerEvent().

[override] bool QProcess::waitForBytesWritten(int msecs = 30000)

Reimplements QIODevice::waitForBytesWritten().

Blocks until data has been written to the process and bytesWritten() has been emitted, or until msecs milliseconds have passed. Returns false if nothing is waiting to be written, the process ended or the wait timed out. Output of the process is read in the meantime.

See also waitForReadyRead() and bytesToWrite().

bool QProcess::waitForFinished(int msecs = 30000)

Blocks until the process has finished and finished() has been emitted, or until msecs milliseconds have passed; a negative value waits indefinitely. Returns true if the process finished; returns false if it already had, failed to start or the wait timed out. Data is read and written while waiting.

See also waitForStarted().

[override] bool QProcess::waitForReadyRead(int msecs = 30000)

Reimplements QIODevice::waitForReadyRead().

Blocks until new data is available on the current read channel and readyRead() has been emitted, or until msecs milliseconds have passed. Returns false if the process ended, failed or the wait timed out. While it waits, the data of both channels is read and input is written.

See also waitForBytesWritten().

bool QProcess::waitForStarted(int msecs = 30000)

Blocks until the process has started and started() has been emitted, or until msecs milliseconds have passed; a negative value waits indefinitely. Returns true if the process started; returns false if it failed to start, was not started, or the wait timed out (the error is then Timedout).

See also waitForFinished() and started().

QString QProcess::workingDirectory() const

Returns the working directory the process will start in. An empty string means the child inherits the working directory of the parent.

See also setWorkingDirectory().

[override, protected] qint64 QProcess::writeData(const char *data, qint64 maxSize)

Reimplements QIODevice::writeData().