CopperSpice API  2.0.0
QProcess Class Reference

The QProcess class is used to start external commands. 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 &childName=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)
 
static bool disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t)
 
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 an external command by launching a separate task in the operating system. This class is an interface to the operating system task management functions. On Unix and Mac OS X these task functions are fork() and exec(). On Windows the OS function CreateProcess() is called.

As an example, on Unix and Mac OS X calling QProcess::start() is responsible for interfacing with the OS.

  • creates a new task by calling fork()
  • calls exec() to run a command like ls or touch

Running a Command

To run a command pass the program 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 –help as two arguments.

QProcess::start() sets the enum ProcessState to the value Starting. When the command is started myProcess enters the Running state and emits the started() signal.

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

When the command exits QProcess returns to the NotRunning state and emits the finished() signal. This signal provides the exit code and status of the command. Call exitCode() or exitStatus() for information about the last command. If an error occurs the error() signal is emitted. Call error() or state() to retrieve additional information.

Reading and Writing

This class allows reading and writing from a command as a sequential I/O device. To write to and read from the command call methods inherited from QIODevice like read(), write(), readLine(), and getChar().

Communicating via Channels

QProcess has two predefined output channels.

  • standard output channel (stdout) contains regular console output
  • standard error channel (stderr) contains the errors printed by the command

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 stdout channel corresponds to the QProcess read channel. The 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 command both use the standard output channel. Call setProcessChannelMode() with MergedChannels before starting the command to activate this feature. You also have the option of forwarding the output of the running command to the calling, main command, by passing ForwardedChannels as the argument.

Certain commands need a special environment variabal to be set in order to work correctly. Environment variables can be set by calling setEnvironment(). To set a working directory call setWorkingDirectory(). By default, commands are run in the current working directory of the CopperSpice application.

Synchronous API

QProcess provides a set of methods which allow this class to be used without an event loop. This is done by suspending the calling thread until certain signals are emitted. Calling these from the main QApplication thread may cause the user interface to freeze.

waitForStarted()
blocks until the command 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 command
waitForFinished()
blocks until the command has finished

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()) { // suspends the main thread until gzip starts
return false;
}
gzip.write("CopperSpice is wonderful");
if (! gzip.waitForFinished()) { // suspends the main thread until gzip is finished
return false;
}
QByteArray result = gzip.readAll();

Windows OS

Some Windows commands like dir are not implemented as a separate executable and therefore can not be started by QProcess. A better solution is to execute the command interpreter and ask the interpreter to execute the command.

See also
QBuffer, QFile

Member Enumeration Documentation

This enum describes the exit status of a QProcess.

ConstantValueDescription
QProcess::NormalExit 0 Exited normally
QProcess::CrashExit 1 Crashed
See also
exitStatus()

This enum describes the 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 task. Default input channel mode of QProcess.
QProcess::ForwardedInputChannel 1 QProcess forwards the input of the CopperSpice application to the running command. The CopperSpice application must not read from standard input while the command is running.
See also
setInputChannelMode()

This enum describes the channels used by the running task. Pass one of these values to setReadChannel() to set the current read channel of QProcess.

ConstantValueDescription
QProcess::StandardOutput0 Standard output (stdout) of the running command
QProcess::StandardError1 Standard error (stderr) of the running command
See also
setReadChannel()

This enum describes the 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 command, keeping standard output and standard error data in separate internal buffers. Select the QProcess current read channel by calling setReadChannel(). Default channel mode of QProcess.
QProcess::MergedChannels1 QProcess merges the output of the running command into the standard output channel (stdout). The standard error channel (stderr) will not receive any data. The standard output and standard error of the running command are interleaved.
QProcess::ForwardedChannels2 QProcess forwards the output of the running command to the CopperSpice application. Anything the command writes to standard output and standard error will be written to the standard output and standard error of the CopperSpice application.
See also
setProcessChannelMode()

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

ConstantValueDescription
QProcess::FailedToStart0 Task failed to start. Either the invoked command is missing, or you may have insufficient permissions to invoke the command.
QProcess::Crashed1 Task crashed some time after starting successfully.
QProcess::Timedout2 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 command. For example, the command may not be running, or it may have closed its input channel.
QProcess::ReadError3 An error occurred when attempting to read from the command. For example, the command 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::NotRunning0 Process is not running.
QProcess::Starting1 Process is starting, but the command has not yet been invoked.
QProcess::Running2 Process is running and is ready for reading and writing.
See also
state()

Constructor & Destructor Documentation

QProcess::QProcess ( QObject parent = nullptr)
explicit

Constructs a new QProcess with the given parent.

QProcess::~QProcess ( )
virtual

Destroys this QProcess. This method will not return until the task is terminated.

Method Documentation

QStringList QProcess::arguments ( ) const

Returns the command line arguments this QProcess was last started with.

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

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

Reimplemented from QIODevice::atEnd()

qint64 QProcess::bytesAvailable ( ) const
overridevirtual

Reimplemented from QIODevice::bytesAvailable()

qint64 QProcess::bytesToWrite ( ) const
overridevirtual

Reimplemented from QIODevice::bytesToWrite()

bool QProcess::canReadLine ( ) const
overridevirtual

This method operates on the current read channel.

See also
readChannel(), setReadChannel()

Reimplemented from QIODevice::canReadLine()

void QProcess::close ( )
overridevirtual

Closes all communication with the last command started by this QProcess and kills the running task. After calling this method QProcess will no longer emit readyRead() and data can no longer be read or written.

Reimplemented from QIODevice::close()

void QProcess::closeReadChannel ( ProcessChannel  channel)

Closes the read channel. After calling this method QProcess will no longer receive data on the channel. Any data which 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 command.

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 command. After calling this method any attempts to write to the command 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

Returns the environment which QProcess will use when starting a command, 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 command will be used.

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

Returns the type of error which occurred last.

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

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

int QProcess::execute ( const QString command)
static

Starts command in a new task. 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 task. This method then waits for the command to finish and returns the exit code of the command. Any data the new command writes to the console is captured by QProcess. The environment and working directory are inherited from the calling command.

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

On Windows, arguments which contain spaces must be wrapped in quotes.

int QProcess::exitCode ( ) const

Returns the exit code of the last command which finished.

QProcess::ExitStatus QProcess::exitStatus ( ) const

Returns the exit status of the last command which finished.

On Windows, if the task 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 command finishes. The parameter exitCode is the exit code of the command and exitStatus is the exit status for the task. After the commands has finished, the buffers in QProcess are still intact. This means you can still read any data which the command may have written before it finished.

Since the finished() signal is overloaded. Use the following syntax to connect this signal to some slot, which in this example is a lambda expression.

// QProcess myProcess
connect(myProcess, cs_mp_cast<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 command finishes. The exitCode is the exit code of the command and exitStatus is the exit status of the task. The slot can read any data the comman 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()

void QProcess::kill ( )
slot

Kills the current task causing it to exit immediately. On Unix and Mac OS X the SIGKILL signal is sent to the task. On Windows kill() uses TerminateProcess().

QString QProcess::nativeArguments ( ) const

Returns the additional native command line arguments. This method is only available on Windows.

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

Q_PID QProcess::pid ( ) const

Returns the native task identifier for the running command, if available. If no command is currently running then a value of 0 is returned.

ProcessChannelMode QProcess::processChannelMode ( ) const

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

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

Returns a list of environment variables QProcess will use when starting a command. An empty list is returned if no environment variables were set by calling setEnvironment() or setProcessEnvironment(). In this case, the environment variables are inherited from your system environment.

See also
setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()
qint64 QProcess::processId ( ) const

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

QString QProcess::program ( ) const

Returns the name of the command most recently started by this QProcess.

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 command 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 command 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. Equivalent to calling to processChannelMode().
See also
setReadChannelMode(), processChannelMode()
qint64 QProcess::readData ( char *  data,
qint64  maxlen 
)
overrideprotectedvirtual
void QProcess::readyReadStandardError ( )
signal

This signal is emitted when the command 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 command 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 command. This method must be called before calling start().

This method takes a list of strings and automatically handles quoting the arguments which contain spaces to ensure they are passed correctly across different operating systems.

On Windows, the arguments are quoted to be compatible with the CommandLineToArgvW() Windows function. For more information refer to the documentation for setNativeArguments().

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

Sets one or more environment variables which QProcess will use when starting a command. Each element of the given environment must contain a key and a value, separated by an equal sign.

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

QProcess process;
data << "TMPDIR=C:\\MyApp\\tmp"; // add an environment variable
data.replaceInStrings(QRegularExpression("^PATH=(.*)", QPatternOption::CaseInsensitiveOption), "PATH=\\1;C:\\Bin");
process.setEnvironment(data);
process.start("myapp");
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. This method is only available on Windows.

This method is necessary when setArguments() can not handle complex or non-standard argument parsing for certain programs. One notable program which does not follow the Windows CommandLineToArgvW() syntax is cmd.exe and therefore all batch scripts.

The value of arguments is a single raw string which is appended to the command program name and any other arguments previously passed.

See also
nativeArguments(), setArguments()
void QProcess::setProcessChannelMode ( ProcessChannelMode  mode)

Sets the channel mode of the QProcess standard output and standard error channels to mode. The new mode will be used the next time start() is called.

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 one or more environment variables which QProcess will use when starting a command. Each element of the given environment must contain a key and a value.

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

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

On Windows the environment variable names are case insensitive.

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

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

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

Sets the command to use when starting the task. 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 standard error to the given 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.

If setProcessChannelMode() was called with an argument of QProcess::MergedChannels, this function has no effect. Refer to setStandardOutputFile() for more information on how the file is opened.

See also
setStandardInputFile(), setStandardOutputFile(), setStandardOutputProcess()
void QProcess::setStandardInputFile ( const QString fileName)

Redirects the standard input for the command from the file indicated by fileName. When an input redirection is in place the QProcess will be in read only mode. If the file fileName does not exist at the moment start() is called or is not readable, starting the command will fail.

Calling setStandardInputFile() after the command has started has no effect.

See also
setStandardOutputFile(), setStandardErrorFile(), setStandardOutputProcess()
void QProcess::setStandardOutputFile ( const QString fileName,
OpenMode  mode = Truncate 
)

Redirects the 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 command will not start.

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 command has started has no effect.

See also
setStandardInputFile(), setStandardErrorFile(), setStandardOutputProcess()
void QProcess::setStandardOutputProcess ( QProcess *  destination)

Pipes the standard output stream of this QProcess to the standard input stream of the destination.

Example 1

The following is a typical command which might be started from a command prompt.

command1 | command2

Example 2

The following code uses QProcess to accomplish the same thing from within a CopperSpice application.

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

This method is only available on Unix or Mac OS X. It will be called after the "fork" and before the "exec". Do not call exit() without calling finished() first.

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

Sets the working directory to dir. QProcess will start the command in this given directory. If this method is not called, the default behavior is to start the command in the current working directory.

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

Starts the given command and passes the given arguments. The OpenMode is set to mode.

QProcess will immediately enter the Starting state. If the command starts successfully QProcess will emit the started() signal, otherwise errorOccurred() will be emitted. Commands are started asynchronously which means the started() and errorOccurred() signals may be delayed. Calling waitForStarted() will not return until the command has started or has failed to start.

If the QProcess is already running then a warning may be printed on the console and the existing command will continue running unaffected.

On Windows, the arguments are quoted to be compatible with the CommandLineToArgvW() Windows function. For more information refer to the documentation for setNativeArguments().

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

Starts the given command. The OpenMode is set to mode.

The specified command is a single string of text which must contain 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.

On Windows, the arguments are quoted to be compatible with the CommandLineToArgvW() Windows function. For more information refer to the documentation for setNativeArguments().

Example 1

Arguments which contain spaces must be quoted. All quotes need to be must be preceded by a backslash.

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

Example 2

Passing an argument which contains a quote character in the command string requires 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()
bool QProcess::startDetached ( const QString command)
static

Starts command in a new task. 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 any arguments containing spaces are correctly supplied to the new command.

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

Starts command with the given arguments in a new task. Arguments which contain spaces are not passed to the command as separate arguments. Returns true on success, otherwise returns false. If this method is successful pid is set to the task identifier of the started command.

The task will be started in the directory workingDirectory.

Once the task is running, QProcess will detach the task from the CopperSpice application. If the CopperSpice application exits, the detached task will continue executing the command.

void QProcess::started ( )
signal

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

ProcessState QProcess::state ( ) const

Returns the current state of QProcess.

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 CopperSpice application as a list of key=value pairs.

This method does not cache the system environment. It is possible to obtain an updated version of the environment if C library functions like setenv or putenv have been called.

Calling QProcessEnvironment::systemEnvironment() is more efficient than calling this method.

// returns: "PATH=/usr/bin:/usr/local/bin", "USER=bill", "HOME=/home/bill"
See also
QProcessEnvironment::systemEnvironment(), environment(), setEnvironment()
void QProcess::terminate ( )
slot

Sends a request to terminate the task. The command may not exit as a result of calling this method.

On Unix and Mac OS X the SIGTERM signal is sent to the task.

On Windows, terminate() posts a WM_CLOSE message to all toplevel windows of the task and then to the main thread of the task itself. 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
bool QProcess::waitForFinished ( int  msecs = 30000)

Blocks until the command has finished and the finished() signal has been emitted or until msecs milliseconds have passed. If the value fo msecs is -1 this method will not time out.

Returns true if the command 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 thread might cause the user interface to freeze.
See also
finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()
bool QProcess::waitForReadyRead ( int  msecs = 30000)
overridevirtual

Reimplemented from QIODevice::waitForReadyRead()

bool QProcess::waitForStarted ( int  msecs = 30000)

Blocks until the command has started and the started() signal has been emitted, or until msecs milliseconds have passed. If the value of msecs is -1 this method will not time out.

Returns true if the command was started successfully, 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.

Warning
Calling this method from the main thread might cause the 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 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

Friends And Related Function Documentation

typedef Q_PID ( )
related

Typedef for the identifier which is used to represent a task. On Unix and Mac OS X this corresponds to qint64, on Windows it corresponds to _PROCESS_INFORMATION*.

See also
QProcess::pid()