CopperSpice API  1.7.2
QProcess Class Reference

Used to start external programs and communicate with them. More...

Inheritance diagram for QProcess:
QIODevice QObject

Public Types

enum  ExitStatus
 
enum  InputChannelMode
 
enum  ProcessChannel
 
enum  ProcessChannelMode
 
enum  ProcessError
 
enum  ProcessState
 
- Public Types inherited from QIODevice
enum  OpenModeFlag
 

Public Signals

void errorOccurred (QProcess::ProcessError error)
 
void finished (int exitCode)
 
void finished (int exitCode, QProcess::ExitStatus exitStatus)
 
void readyReadStandardError ()
 
void readyReadStandardOutput ()
 
void started ()
 
void stateChanged (QProcess::ProcessState newState)
 
- Public Signals inherited from QIODevice
void aboutToClose ()
 
void bytesWritten (qint64 bytes)
 
void readChannelFinished ()
 
void readyRead ()
 
- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 

Public Slots

void kill ()
 
void terminate ()
 
- Public Slots inherited from QObject
void deleteLater ()
 

Public Methods

 QProcess (QObject *parent=nullptr)
 
virtual ~QProcess ()
 
QStringList arguments () const
 
bool atEnd () const override
 
qint64 bytesAvailable () const override
 
qint64 bytesToWrite () const override
 
bool canReadLine () const override
 
void close () override
 
void closeReadChannel (ProcessChannel channel)
 
void closeWriteChannel ()
 
QStringList environment () const
 
QProcess::ProcessError error () const
 
int exitCode () const
 
QProcess::ExitStatus exitStatus () const
 
InputChannelMode inputChannelMode () const
 
bool isSequential () const override
 
QString nativeArguments () const
 
bool open (OpenMode mode=ReadWrite) override
 
Q_PID pid () const
 
ProcessChannelMode processChannelMode () const
 
QProcessEnvironment processEnvironment () const
 
qint64 processId () const
 
QString program () const
 
QByteArray readAllStandardError ()
 
QByteArray readAllStandardOutput ()
 
ProcessChannel readChannel () const
 
ProcessChannelMode readChannelMode () const
 
void setArguments (const QStringList &arguments)
 
void setEnvironment (const QStringList &environment)
 
void setInputChannelMode (InputChannelMode mode)
 
void setNativeArguments (const QString &arguments)
 
void setProcessChannelMode (ProcessChannelMode mode)
 
void setProcessEnvironment (const QProcessEnvironment &environment)
 
void setProgram (const QString &command)
 
void setReadChannel (ProcessChannel channel)
 
void setReadChannelMode (ProcessChannelMode mode)
 
void setStandardErrorFile (const QString &fileName, OpenMode mode=Truncate)
 
void setStandardInputFile (const QString &fileName)
 
void setStandardOutputFile (const QString &fileName, OpenMode mode=Truncate)
 
void setStandardOutputProcess (QProcess *destination)
 
void setWorkingDirectory (const QString &dir)
 
void start (const QString &command, const QStringList &arguments, OpenMode mode=ReadWrite)
 
void start (const QString &command, OpenMode mode=ReadWrite)
 
void start (OpenMode mode=ReadWrite)
 
QProcess::ProcessState state () const
 
bool waitForBytesWritten (int msecs=30000) override
 
bool waitForFinished (int msecs=30000)
 
bool waitForReadyRead (int msecs=30000) override
 
bool waitForStarted (int msecs=30000)
 
QString workingDirectory () const
 
- Public Methods inherited from QIODevice
 QIODevice ()
 
 QIODevice (QObject *parent)
 
virtual ~QIODevice ()
 
QString errorString () const
 
bool getChar (char *c)
 
bool isOpen () const
 
bool isReadable () const
 
bool isTextModeEnabled () const
 
bool isWritable () const
 
OpenMode openMode () const
 
qint64 peek (char *data, qint64 maxSize)
 
QByteArray peek (qint64 maxSize)
 
virtual qint64 pos () const
 
bool putChar (char c)
 
qint64 read (char *data, qint64 maxSize)
 
QByteArray read (qint64 maxSize)
 
QByteArray readAll ()
 
qint64 readLine (char *data, qint64 maxSize)
 
QByteArray readLine (qint64 maxSize=0)
 
virtual bool reset ()
 
virtual bool seek (qint64 pos)
 
void setTextModeEnabled (bool enabled)
 
virtual qint64 size () const
 
void ungetChar (char c)
 
qint64 write (const char *data)
 
qint64 write (const char *data, qint64 maxSize)
 
qint64 write (const QByteArray &data)
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &objName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Static Public Methods

static int execute (const QString &command)
 
static int execute (const QString &command, const QStringList &arguments)
 
static QString nullDevice ()
 
static bool startDetached (const QString &command)
 
static bool startDetached (const QString &command, const QStringList &arguments, const QString &workingDirectory=QString (), qint64 *pid=nullptr)
 
static QStringList systemEnvironment ()
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 

Protected Methods

qint64 readData (char *data, qint64 maxlen) override
 
void setProcessState (ProcessState state)
 
virtual void setupChildProcess ()
 
qint64 writeData (const char *data, qint64 len) override
 
- Protected Methods inherited from QIODevice
virtual qint64 readLineData (char *data, qint64 maxSize)
 
void setErrorString (const QString &errorString)
 
void setOpenMode (OpenMode openMode)
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 

Related Functions

These are not member functions

typedef Q_PID
 

Additional Inherited Members

- Public Typedefs inherited from QIODevice
using OpenMode = QFlags< OpenModeFlag >
 
- Properties inherited from QObject
 objectName
 

Detailed Description

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

Running a Process

To start a process pass the command name and any required arguments which are necessary. Arguments are supplied as individual strings in a QStringList. The following code runs "someUtility" and passes –version and –gui as two arguments.

QString cmdName = "./demo/examples/other/someUtility";
arguments << "--version" << "--gui";
QProcess *myProcess = new QProcess(parent);
myProcess->start(cmdName, arguments);

QProcess then enters the Starting state. WHen the process is started myProcess enters the Running state and emits the started() signal.

This class 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 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 QFtp.

When the process exits QProcess returns to the NotRunning state and emits the finished() signal. This signal provides the exit code and status of the process as arguments. You can call exitCode() to obtain the exit code of the last process that finished and exitStatus() to obtain its exit status. If an error occurs the error() signal is emitted. Call error() or state() to retrieve additional information.

Communicating via Channels

Processes have two predefined output channels.

  • standard output channel (stdout) contains regular console output
  • standard error channel (stderr) contains the errors 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. The process stdout channel corresponds to the QProcess read channel. The process stdin channel corresponds to the QProcess write channels.

QProcess can merge the two output channels so 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.

Certain processes need special environment settings in order to operate. You can set environment variables for your process by calling setEnvironment(). To set a working directory, call setWorkingDirectory(). By default, processes are run in the current working directory of the calling process.

Synchronous Process API

QProcess provides a set of methods which allow it to be used without an event loop, by suspending the calling thread until certain signals are emitted:

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 "CopperSpice is wonderful" without an event loop.

QProcess gzip;
gzip.start("gzip", QStringList() << "-c");
if (! gzip.waitForStarted()) {
return false;
}
gzip.write("CopperSpice is wonderful");
if (! gzip.waitForFinished()) {
return false;
}
QByteArray result = gzip.readAll();

Notes for Windows Users

Some Windows commands like dir are not provided by separate applications, they are intended to be run by the command interpreter. If you attempt to use QProcess to execute these commands directly it will not work. One possible solution is to execute the command interpreter itself and ask the interpreter to execute the desired command.

See also
QBuffer, QFile, QTcpSocket

Member Enumeration Documentation

This enum describes the different exit statuses of QProcess.

ConstantValueDescription
QProcess::NormalExit0The process exited normally.
QProcess::CrashExit1The process crashed.
See also
exitStatus()

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::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.
See also
setInputChannelMode()

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()

This enum describes the process channel modes of QProcess. Pass one of these values to setProcessChannelMode() to set the current read channel mode.

ConstantValueDescription
QProcess::SeparateChannels0 QProcess manages the output of the running process, keeping standard output and standard error data in separate internal buffers. You can select the QProcess current read channel by calling setReadChannel(). This is the default channel mode of QProcess.
QProcess::MergedChannels1 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.
QProcess::ForwardedChannels2 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.
See also
setProcessChannelMode()

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

ConstantValueDescription
QProcess::FailedToStart0 Process failed to start. Either the invoked command is missing, or you may have insufficient permissions to invoke the command.
QProcess::Crashed1 The process crashed some time after starting successfully.
QProcess::Timedout2 The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.
QProcess::WriteError4 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::ReadError3 An error occurred when attempting to read from the process. For example, the process may not be running.
QProcess::UnknownError5 An unknown error occurred. This is the default return value of error().
See also
error()

This enum describes the different states of QProcess.

ConstantValueDescription
QProcess::NotRunning0Process is not running.
QProcess::Starting1Process is starting, but the command has not yet been invoked.
QProcess::Running2Process is running and is ready for reading and writing.
See also
state()

Constructor & Destructor Documentation

QProcess::QProcess ( QObject parent = nullptr)
explicit

Constructs a QProcess object with the given parent.

QProcess::~QProcess ( )
virtual

Destroys the QProcess object. This method will not return until the process is terminated.

Method Documentation

QStringList QProcess::arguments ( ) const

Returns the command line arguments the process was last started with.

See also
setArguments(), start()
bool QProcess::atEnd ( ) const
overridevirtual

Returns true if the process is not running and no more data is available for reading, otherwise returns false.

Reimplemented from QIODevice.

qint64 QProcess::bytesAvailable ( ) const
overridevirtual

Reimplemented from QIODevice::bytesAvailable().

Reimplemented from QIODevice.

qint64 QProcess::bytesToWrite ( ) const
overridevirtual

Reimplemented from QIODevice::bytesToWrite().

Reimplemented from QIODevice.

bool QProcess::canReadLine ( ) const
overridevirtual

This method operates on the current read channel.

See also
readChannel(), setReadChannel()

Reimplemented from QIODevice.

void QProcess::close ( )
overridevirtual

Closes all communication with the process and kills it. After calling this method QProcess will no longer emit readyRead() and data can no longer be read or written.

Reimplemented from QIODevice.

void QProcess::closeReadChannel ( ProcessChannel  channel)

Closes the read channel channel. After calling this method, QProcess will no longer receive data on the channel. Any data that has already been received is still available for reading. Call this method to save memory, if you are not interested in the output of the process.

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 method any attempts to write to the process will fail.

Closing the write channel is necessary for commands which read input data until the channel has been closed. For example, the "more" command is used to display text data in a console on both Unix and Windows. It will not display any text data until the write channel for myProcess has been closed.

The write channel is implicitly opened when start() is called.

QProcess myProcess;
myProcess.start("more");
myProcess.write("Text to display");
myProcess.closeWriteChannel(); // QProcess will emit readyRead()
See also
closeReadChannel()
QStringList QProcess::environment ( ) const

This function is deprecated.

Returns the environment that QProcess will use when starting a process, or an empty QStringList if no environment has been set using setEnvironment() or setEnvironmentHash(). If no environment has been set, the environment of the calling process will be used.

See also
processEnvironment(), setEnvironment(), systemEnvironment()
QProcess::ProcessError QProcess::error ( ) const

Returns the type of error that occurred last.

See also
state()
void QProcess::errorOccurred ( QProcess::ProcessError  error)
signal

This signal is emitted when an error occurs with the process. The specified error describes the type of error which occurred.

int QProcess::execute ( const QString command)
static

Starts command in a new process. The value for command is a single string of text containing both the program name and any required arguments which are separated by one or more spaces.

int QProcess::execute ( const QString command,
const QStringList arguments 
)
static

Starts command with the passed arguments in a new process. Then waits for it to finish and return 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. On Windows, arguments that contain spaces must be wrapped in quotes.

If the process can not be started, -2 is returned. If the process crashes, -1 is returned. Otherwise, the process' exit code is returned.

int QProcess::exitCode ( ) const

Returns the exit code of the last process that finished.

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 method will still return NormalExit unless the exit code is less than 0.

void QProcess::finished ( int  exitCode)
signal

This signal is emitted when the process finishes. The parameter 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.

Signal finished is overloaded in this class. To connect to this signal using the function pointer syntax, specify the signal type in a static cast as shown in this example

connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
[=](int exitCode, QProcess::ExitStatus exitStatus){ /* ... */ });
void QProcess::finished ( int  exitCode,
QProcess::ExitStatus  exitStatus 
)
signal

This signal is emitted when the process finishes. exitCode is the exit code of the process, 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()
InputChannelMode QProcess::inputChannelMode ( ) const

Returns the channel mode of the QProcess standard input channel.

See also
setInputChannelMode(), InputChannelMode
bool QProcess::isSequential ( ) const
overridevirtual

Reimplemented from QIODevice::isSequential().

Reimplemented from QIODevice.

void QProcess::kill ( )
slot

Kills the current process, causing it to exit immediately.

On Windows kill() uses TerminateProcess, and on Unix and Mac OS X, the SIGKILL signal is sent to the process.

QString QProcess::nativeArguments ( ) const

Returns the additional native command line arguments.

Note
This method is available only on the Windows platforms.
See also
setNativeArguments()
QString QProcess::nullDevice ( )
static

The null device of the operating system. The returned file path uses native directory separators.

See also
QProcess::setStandardInputFile(), QProcess::setStandardOutputFile(), QProcess::setStandardErrorFile()
bool QProcess::open ( OpenMode  mode = ReadWrite)
overridevirtual

Opens the device and sets its OpenMode to mode. Returns true if successful, otherwise returns false. This method should be called from any existing reimplementation of open() or other functions that open the device.

See also
openMode(), OpenMode

Reimplemented from QIODevice.

Q_PID QProcess::pid ( ) const

Returns the native process identifier for the running process, if available. If no process is currently running, 0 is returned.

ProcessChannelMode QProcess::processChannelMode ( ) const

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

See also
setProcessChannelMode(), ProcessChannelMode, setReadChannel()
QProcessEnvironment QProcess::processEnvironment ( ) const

Returns the environment that QProcess will use when starting a 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
setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
qint64 QProcess::processId ( ) const

Returns the native process identifier for the running process, if available. If no process is currently running, 0 is returned.

QString QProcess::program ( ) const

Returns the name of the command most recently started.

See also
setProgram(), start()
QByteArray QProcess::readAllStandardError ( )

Regardless of the current read channel, this method returns all data available from the standard error of the process as a QByteArray.

See also
readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()
QByteArray QProcess::readAllStandardOutput ( )

Regardless of the current read channel, this method returns all data available from the standard output of the process as a QByteArray.

See also
readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()
ProcessChannel QProcess::readChannel ( ) const

Returns the current read channel of the QProcess.

See also
setReadChannel()
ProcessChannelMode QProcess::readChannelMode ( ) const
deprecated
Deprecated:
Returns the read channel mode of the QProcess. This function is equivalent to processChannelMode()
See also
setReadChannelMode(), processChannelMode()
qint64 QProcess::readData ( char *  data,
qint64  maxlen 
)
overrideprotectedvirtual

Reimplemented from QIODevice::readData().

Implements QIODevice.

void QProcess::readyReadStandardError ( )
signal

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(), readChannel()
void QProcess::readyReadStandardOutput ( )
signal

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(), readChannel()
void QProcess::setArguments ( const QStringList arguments)

Sets the arguments to use when starting the process. This method must be called before start().

See also
start(), setProgram(), arguments()
void QProcess::setEnvironment ( const QStringList environment)

Sets the environment that QProcess will use when starting a process to the environment specified which consists of a list of key=value pairs.

For example, the following code adds the C:\BIN directory to the list of executable paths (PATHS) on Windows:

QProcess process;
env << "TMPDIR=C:\MyApp\temp"; // Add an environment variable
env.replaceInStrings(QRegularExpression("^PATH=(.*)", QPatternOption::CaseInsensitiveOption), "PATH=\1;C:\Bin");
process.setEnvironment(env);
process.start("myapp");

This method has been deprecated, use setProcessEnvironment() instead.

See also
environment(), setProcessEnvironment(), systemEnvironment()
void QProcess::setInputChannelMode ( 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.

See also
inputChannelMode(), InputChannelMode
void QProcess::setNativeArguments ( const QString arguments)

Sets additional native command line arguments.

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 can not be passed via the QProcess 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.

Note
This method is available only on Windows platforms.
See also
nativeArguments()
void QProcess::setProcessChannelMode ( 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() << "-j2");
if (! builder.waitForFinished()) {
qDebug() << "Make failed:" << builder.errorString();
} else {
qDebug() << "Make output:" << builder.readAll();
}
See also
processChannelMode(), ProcessChannelMode, setReadChannel()
void QProcess::setProcessEnvironment ( const QProcessEnvironment environment)

Sets the environment that QProcess will use when starting a process to the environment object.

For example, the following code adds the C:\BIN directory to the list of executable paths (PATHS) on Windows and sets TMPDIR:

QProcess process;
env.insert("TMPDIR", "C:\MyApp\temp"); // Add an environment variable
env.insert("PATH", env.value("Path") + ";C:\Bin");
process.setProcessEnvironment(env);
process.start("myapp");

On Windows the environment variable names are case-insensitive.

See also
processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()
void QProcess::setProcessState ( ProcessState  state)
protected

Sets the current state of the QProcess to the state specified.

See also
state()
void QProcess::setProgram ( const QString command)

Sets the command to use when starting the process. This method must be called before start().

See also
start(), setArguments(), program()
void QProcess::setReadChannel ( 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
readChannel()
void QProcess::setReadChannelMode ( ProcessChannelMode  mode)
deprecated
void QProcess::setStandardErrorFile ( const QString fileName,
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.

Refer to 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
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).

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
setStandardOutputFile(), setStandardErrorFile(), setStandardOutputProcess()
void QProcess::setStandardOutputFile ( const QString fileName,
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().

If the file fileName does not exist at the moment start() is called it will be created. If it can not 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
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 QProcesses with the following code:

QProcess process1;
QProcess process2;
process1.setStandardOutputProcess(&process2);
process1.start("command1");
process2.start("command2");
void QProcess::setupChildProcess ( )
protectedvirtual

This method is called in the child process context just before the command is executed on Unix or Mac OS X.

class SandboxProcess : public QProcess
{
protected:
...
};
void SandboxProcess::setupChildProcess() {
// Drop all privileges in the child process, and enter a chroot jail
#if defined Q_OS_UNIX
::setgroups(0, 0);
::chroot("/etc/safe");
::chdir("/");
::setgid(safeGid);
::setuid(safeUid);
::umask(0);
#endif
}

You can not exit the process by calling exit(). If the command can not be executed emit finished() and then call exit().

Warning
This method is called by QProcess on Unix and OS X only. On Windows it is not called.
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.

See also
workingDirectory(), start()
void QProcess::start ( const QString command,
const QStringList arguments,
OpenMode  mode = ReadWrite 
)

Starts the given command in a new process and passes the command line arguments in arguments. The OpenMode is set to mode. No further splitting of the arguments is performed.

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.

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.

On Windows the arguments are quoted and joined into a command line that is compatible with the CommandLineToArgvW() Windows function. For commands which have different command line quoting requirements you will need to use setNativeArguments(). One notable program that does not follow the CommandLineToArgvW() rules is cmd.exe and, by consequence, all batch scripts.

See also
processId(), started(), waitForStarted(), setNativeArguments()
void QProcess::start ( const QString command,
OpenMode  mode = ReadWrite 
)

Starts command in a new process. The OpenMode is set to mode. The parameter command is a single string of text containing both the command name and its arguments. The arguments are separated by one or more spaces. After the command string has been split and unquoted this method behaves like the overload which takes the arguments as a string list.

You can disable this overload by defining QT_NO_PROCESS_COMBINED_ARGUMENT_START when you compile your applications. This can be useful if you want to ensure that you are not splitting arguments unintentionally, for example. In virtually all cases, using the other overload is the preferred method.

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 method.

QProcess process;
process.start("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.

QProcess process;
process.start("dir \"My Documents\"");

Literal quotes in the command string are represented by triple quotes.

QProcess process;
process.start("dir \"Epic 12\"\"\" Singles\"");
void QProcess::start ( OpenMode  mode = ReadWrite)

Starts the command set by setProgram() with arguments set by setArguments(). The OpenMode is set to mode.

See also
open(), setProgram(), setArguments()
bool QProcess::startDetached ( const QString command)
static

Starts command in a new process. The command is a string of text containing both the program name and its arguments. The arguments are separated by one or more spaces. The command can also contain quotes to ensure that arguments containing spaces are correctly supplied to the new process.

bool QProcess::startDetached ( const QString command,
const QStringList arguments,
const QString workingDirectory = QString(),
qint64 pid = nullptr 
)
static

Starts command 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 live. If this method is successful *pid is set to the process identifier of the started process.

Arguments which contain spaces are not passed to the process as separate arguments.

Unix: The started process will run in its own session and act like a daemon.

Windows: Arguments that contain spaces are wrapped in quotes. The started process will run as a regular standalone process.

The process will be started in the directory workingDirectory.

void QProcess::started ( )
signal

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

ProcessState QProcess::state ( ) const

Returns the current state of the process.

See also
stateChanged(), error()
void QProcess::stateChanged ( QProcess::ProcessState  newState)
signal

This signal is emitted whenever the state of QProcess changes. The newState argument is the state QProcess changed to.

QStringList QProcess::systemEnvironment ( )
static

Returns the environment of the calling process as a list of key=value pairs.

// returns: "PATH=/usr/bin:/usr/local/bin", "USER=fred", "HOME=/home/fred"

This method does not cache the system environment. It possible to obtain an updated version of the environment if C library functions like setenv or putenv have been called. Repeated calls to this method will recreate the list of environment variables which is a non-trivial operation.

It is recommended to use QProcessEnvironment::systemEnvironment() rather than this method.

See also
QProcessEnvironment::systemEnvironment(), environment(), setEnvironment()
void QProcess::terminate ( )
slot

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 toplevel windows of the process and then to the main thread of the process itself. On Unix and Mac OS X 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().

bool QProcess::waitForBytesWritten ( int  msecs = 30000)
overridevirtual

For buffered devices, this method waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, This method will not time out. For unbuffered devices, it returns immediately.

Returns true if a payload of data was written to the device, otherwise returns false (i.e. if the operation timed out, or if an error occurred).

This method 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. If called from within a slot connected to the bytesWritten() signal, bytesWritten() will not be re-emitted.

Reimplement this method to provide a blocking API for a custom device. The default implementation does nothing, and returns false.

Warning
Calling this method from the main (GUI) thread might cause your user interface to freeze.
See also
waitForReadyRead()

Reimplemented from QIODevice.

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. If msecs is -1 this method will not time out.

Returns true if the process finished, otherwise returns false. This method will return false if the operation timed out, if an error occurred or if this QProcess is already finished.

This method 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.

Warning
Calling this method from the main (GUI) thread might cause your user interface to freeze.
See also
finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
bool QProcess::waitForReadyRead ( int  msecs = 30000)
overridevirtual

Blocks until new data is available for reading and the readyRead() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, this method will not time out. Returns true if new data is available for reading, otherwise returns false.

This method 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. If called from within a slot connected to the readyRead() signal, readyRead() will not be reemitted.

Reimplement this method to provide a blocking API for a custom device. The default implementation does nothing, and returns false.

Warning
Calling this method from the main (GUI) thread might cause your user interface to freeze.
See also
waitForBytesWritten()

Reimplemented from QIODevice.

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. If msecs is -1 this method will not time out.

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.

Warning
Calling this method from the main (GUI) thread might cause your user interface to freeze.
See also
started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()
QString QProcess::workingDirectory ( ) const

If QProcess has been assigned a working directory, this method returns the working directory that the QProcess will enter before the command has started. Otherwise an empty string is returned, and QProcess will use the application's current working directory instead.

See also
setWorkingDirectory()
qint64 QProcess::writeData ( const char *  data,
qint64  len 
)
overrideprotectedvirtual

Reimplemented from QIODevice::writeData().

Implements QIODevice.

Friends And Related Function Documentation

typedef Q_PID ( )
related

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()