Qt 4.8
Public Types | Public Slots | Signals | Public Functions | Static Public Functions | Protected Functions | Friends | Related Functions | List of all members
QProcess Class Reference

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

#include <qprocess.h>

Inheritance diagram for QProcess:
QIODevice QObject

Public Types

enum  ExitStatus { NormalExit, CrashExit }
 This enum describes the different exit statuses of QProcess. More...
 
enum  ProcessChannel { StandardOutput, StandardError }
 This enum describes the process channels used by the running process. More...
 
enum  ProcessChannelMode { SeparateChannels, MergedChannels, ForwardedChannels }
 This enum describes the process channel modes of QProcess. More...
 
enum  ProcessError {
  FailedToStart, Crashed, Timedout, ReadError,
  WriteError, UnknownError
}
 This enum describes the different types of errors that are reported by QProcess. More...
 
enum  ProcessState { NotRunning, Starting, Running }
 This enum describes the different states of QProcess. More...
 
- Public Types inherited from QIODevice
enum  OpenModeFlag {
  NotOpen = 0x0000, ReadOnly = 0x0001, WriteOnly = 0x0002, ReadWrite = ReadOnly | WriteOnly,
  Append = 0x0004, Truncate = 0x0008, Text = 0x0010, Unbuffered = 0x0020
}
 This enum is used with open() to describe the mode in which a device is opened. More...
 

Public Slots

void kill ()
 Kills the current process, causing it to exit immediately. More...
 
void terminate ()
 Attempts to terminate the process. More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 

Signals

void error (QProcess::ProcessError error)
 This signal is emitted when an error occurs with the process. More...
 
void finished (int exitCode)
 Use finished(int exitCode, QProcess::ExitStatus status) instead. More...
 
void finished (int exitCode, QProcess::ExitStatus exitStatus)
 This signal is emitted when the process finishes. More...
 
void readyReadStandardError ()
 This signal is emitted when the process has made new data available through its standard error channel (stderr). More...
 
void readyReadStandardOutput ()
 This signal is emitted when the process has made new data available through its standard output channel (stdout). More...
 
void started ()
 This signal is emitted by QProcess when the process has started, and state() returns Running . More...
 
void stateChanged (QProcess::ProcessState state)
 This signal is emitted whenever the state of QProcess changes. More...
 
- Signals inherited from QIODevice
void aboutToClose ()
 This signal is emitted when the device is about to close. More...
 
void bytesWritten (qint64 bytes)
 This signal is emitted every time a payload of data has been written to the device. More...
 
void readChannelFinished ()
 This signal is emitted when the input (reading) stream is closed in this device. More...
 
void readyRead ()
 This signal is emitted once every time new data is available for reading from the device. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

bool atEnd () const
 Returns true if the process is not running, and no more data is available for reading; otherwise returns false. More...
 
qint64 bytesAvailable () const
 Reimplemented Function More...
 
qint64 bytesToWrite () const
 Reimplemented Function More...
 
bool canReadLine () const
 This function operates on the current read channel. More...
 
void close ()
 Closes all communication with the process and kills it. More...
 
void closeReadChannel (ProcessChannel channel)
 Closes the read channel channel. More...
 
void closeWriteChannel ()
 Schedules the write channel of QProcess to be closed. More...
 
QStringList environment () const
 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(). More...
 
QProcess::ProcessError error () const
 Returns the type of error that occurred last. More...
 
int exitCode () const
 Returns the exit code of the last process that finished. More...
 
QProcess::ExitStatus exitStatus () const
 Returns the exit status of the last process that finished. More...
 
bool isSequential () const
 Reimplemented Function More...
 
QString nativeArguments () const
 Returns the additional native command line arguments for the program. More...
 
Q_PID pid () const
 Returns the native process identifier for the running process, if available. More...
 
ProcessChannelMode processChannelMode () const
 Returns the channel mode of the QProcess standard output and standard error channels. More...
 
QProcessEnvironment 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(). More...
 
 QProcess (QObject *parent=0)
 Constructs a QProcess object with the given parent. More...
 
QByteArray readAllStandardError ()
 Regardless of the current read channel, this function returns all data available from the standard error of the process as a QByteArray. More...
 
QByteArray readAllStandardOutput ()
 Regardless of the current read channel, this function returns all data available from the standard output of the process as a QByteArray. More...
 
ProcessChannel readChannel () const
 Returns the current read channel of the QProcess. More...
 
ProcessChannelMode readChannelMode () const
 Returns the read channel mode of the QProcess. More...
 
void 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. More...
 
void setNativeArguments (const QString &arguments)
 Sets additional native command line arguments for the program. More...
 
void setProcessChannelMode (ProcessChannelMode mode)
 Sets the channel mode of the QProcess standard output and standard error channels to the mode specified. More...
 
void setProcessEnvironment (const QProcessEnvironment &environment)
 Sets the environment that QProcess will use when starting a process to the environment object. More...
 
void setReadChannel (ProcessChannel channel)
 Sets the current read channel of the QProcess to the given channel. More...
 
void setReadChannelMode (ProcessChannelMode mode)
 Use setProcessChannelMode(mode) instead. More...
 
void setStandardErrorFile (const QString &fileName, OpenMode mode=Truncate)
 Redirects the process' standard error to the file fileName. More...
 
void setStandardInputFile (const QString &fileName)
 Redirects the process' standard input to the file indicated by fileName. More...
 
void setStandardOutputFile (const QString &fileName, OpenMode mode=Truncate)
 Redirects the process' standard output to the file fileName. More...
 
void setStandardOutputProcess (QProcess *destination)
 Pipes the standard output stream of this process to the destination process' standard input. More...
 
void setWorkingDirectory (const QString &dir)
 Sets the working directory to dir. More...
 
void start (const QString &program, const QStringList &arguments, OpenMode mode=ReadWrite)
 Starts the given program in a new process, if none is already running, passing the command line arguments in arguments. More...
 
void start (const QString &program, OpenMode mode=ReadWrite)
 Starts the program program in a new process, if one is not already running. More...
 
QProcess::ProcessState state () const
 Returns the current state of the process. More...
 
bool waitForBytesWritten (int msecs=30000)
 Reimplemented Function More...
 
bool waitForFinished (int msecs=30000)
 Blocks until the process has finished and the finished() signal has been emitted, or until msecs milliseconds have passed. More...
 
bool waitForReadyRead (int msecs=30000)
 Reimplemented Function More...
 
bool waitForStarted (int msecs=30000)
 Blocks until the process has started and the started() signal has been emitted, or until msecs milliseconds have passed. More...
 
QString workingDirectory () const
 If QProcess has been assigned a working directory, this function returns the working directory that the QProcess will enter before the program has started. More...
 
virtual ~QProcess ()
 Destructs the QProcess object, i.e., killing the process. More...
 
- Public Functions inherited from QIODevice
QString errorString () const
 Returns a human-readable description of the last device error that occurred. More...
 
bool getChar (char *c)
 Reads one character from the device and stores it in c. More...
 
bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isReadable () const
 Returns true if data can be read from the device; otherwise returns false. More...
 
bool isTextModeEnabled () const
 Returns true if the Text flag is enabled; otherwise returns false. More...
 
bool isWritable () const
 Returns true if data can be written to the device; otherwise returns false. More...
 
virtual bool open (OpenMode mode)
 Opens the device and sets its OpenMode to mode. More...
 
OpenMode openMode () const
 Returns the mode in which the device has been opened; i.e. More...
 
qint64 peek (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, without side effects (i. More...
 
QByteArray peek (qint64 maxlen)
 Peeks at most maxSize bytes from the device, returning the data peeked as a QByteArray. More...
 
virtual qint64 pos () const
 For random-access devices, this function returns the position that data is written to or read from. More...
 
bool putChar (char c)
 Writes the character c to the device. More...
 
 QIODevice ()
 Constructs a QIODevice object. More...
 
 QIODevice (QObject *parent)
 Constructs a QIODevice object with the given parent. More...
 
qint64 read (char *data, qint64 maxlen)
 Reads at most maxSize bytes from the device into data, and returns the number of bytes read. More...
 
QByteArray read (qint64 maxlen)
 Reads at most maxSize bytes from the device, and returns the data read as a QByteArray. More...
 
QByteArray readAll ()
 Reads all available data from the device, and returns it as a QByteArray. More...
 
qint64 readLine (char *data, qint64 maxlen)
 This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. More...
 
QByteArray readLine (qint64 maxlen=0)
 Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray. More...
 
virtual bool reset ()
 Seeks to the start of input for random-access devices. More...
 
virtual bool seek (qint64 pos)
 For random-access devices, this function sets the current position to pos, returning true on success, or false if an error occurred. More...
 
void setTextModeEnabled (bool enabled)
 If enabled is true, this function sets the Text flag on the device; otherwise the Text flag is removed. More...
 
virtual qint64 size () const
 For open random-access devices, this function returns the size of the device. More...
 
void ungetChar (char c)
 Puts the character c back into the device, and decrements the current position unless the position is 0. More...
 
qint64 write (const char *data, qint64 len)
 Writes at most maxSize bytes of data from data to the device. More...
 
qint64 write (const char *data)
 Writes data from a zero-terminated string of 8-bit characters to the device. More...
 
qint64 write (const QByteArray &data)
 Writes the content of byteArray to the device. More...
 
virtual ~QIODevice ()
 The destructor is virtual, and QIODevice is an abstract base class. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static int execute (const QString &program, const QStringList &arguments)
 Starts the program program with the arguments arguments in a new process, waits for it to finish, and then returns the exit code of the process. More...
 
static int execute (const QString &program)
 Starts the program program in a new process. More...
 
static bool startDetached (const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid=0)
 Starts the program program with the arguments arguments in a new process, and detaches from it. More...
 
static bool startDetached (const QString &program, const QStringList &arguments)
 Starts the program program with the given arguments in a new process, and detaches from it. More...
 
static bool startDetached (const QString &program)
 Starts the program program in a new process. More...
 
static QStringList systemEnvironment ()
 Returns the environment of the calling process as a list of key=value pairs. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Protected Functions

qint64 readData (char *data, qint64 maxlen)
 Reimplemented Function More...
 
void setProcessState (ProcessState state)
 Sets the current state of the QProcess to the state specified. More...
 
virtual void setupChildProcess ()
 This function is called in the child process context just before the program is executed on Unix or Mac OS X (i.e., after fork(), but before execve()). More...
 
qint64 writeData (const char *data, qint64 len)
 Reimplemented Function More...
 
- Protected Functions inherited from QIODevice
 QIODevice (QIODevicePrivate &dd, QObject *parent=0)
 
virtual qint64 readLineData (char *data, qint64 maxlen)
 Reads up to maxSize characters into data and returns the number of characters read. More...
 
void setErrorString (const QString &errorString)
 Sets the human readable description of the last device error that occurred to str. More...
 
void setOpenMode (OpenMode openMode)
 Sets the OpenMode of the device to openMode. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Friends

class QProcessManager
 

Related Functions

(Note that these are not member functions.)

 Q_PID
 

Additional Inherited Members

- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

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

Note
This class or function is reentrant.

Running a Process

To start a process, pass the name and command line arguments of the program you want to run as arguments to start(). Arguments are supplied as individual strings in a QStringList.

For example, the following code snippet runs the analog clock example in the Motif style on X11 platforms by passing strings containing "-style" and "motif" as two items in the list of arguments:

...

QString program = "./path/to/Qt/examples/widgets/analogclock";
QStringList arguments;
arguments << "-style" << "motif";
QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);

QProcess then enters the Starting state, and when the program has started, QProcess enters the Running state and emits started().

QProcess allows you to treat a process as a sequential I/O device. You can write to and read from the process just as you would access a network connection using QTcpSocket. You can then write to the process's standard input by calling write(), and read the standard output by calling read(), readLine(), and getChar(). Because it inherits QIODevice, QProcess can also be used as an input source for QXmlReader, or for generating data to be uploaded using QFtp.

Note
On Windows CE and Symbian, reading and writing to a process is not supported.

When the process exits, QProcess reenters the NotRunning state (the initial state), and emits finished().

The finished() signal provides the exit code and exit status of the process as arguments, and you can also call exitCode() to obtain the exit code of the last process that finished, and exitStatus() to obtain its exit status. If an error occurs at any point in time, QProcess will emit the error() signal. You can also call error() to find the type of error that occurred last, and state() to find the current process state.

Communicating via Channels

Processes have two predefined output channels: The standard output channel (stdout) supplies regular console output, and the standard error channel (stderr) usually supplies the errors that are printed by the process. These channels represent two separate streams of data. You can toggle between them by calling setReadChannel(). QProcess emits readyRead() when data is available on the current read channel. It also emits readyReadStandardOutput() when new standard output data is available, and when new standard error data is available, readyReadStandardError() is emitted. Instead of calling read(), readLine(), or getChar(), you can explicitly read all data from either of the two channels by calling readAllStandardOutput() or readAllStandardError().

The terminology for the channels can be misleading. Be aware that the process's output channels correspond to QProcess's read channels, whereas the process's input channels correspond to QProcess's write channels. This is because what we read using QProcess is the process's output, and what we write becomes the process's input.

QProcess can merge the two output channels, so that standard output and standard error data from the running process both use the standard output channel. Call setProcessChannelMode() with MergedChannels before starting the process to activative 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.

Note
On Symbian, setting environment or working directory is not supported. The working directory will always be the private directory of the running process.
On QNX, setting the working directory may cause all application threads, with the exception of the QProcess caller thread, to temporarily freeze, owing to a limitation in the operating system.

Synchronous Process API

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

Calling these functions from the main thread (the thread that calls QApplication::exec()) may cause your user interface to freeze.

The following example runs gzip to compress the string "Qt rocks!", without an event loop:

QProcess gzip;
gzip.start("gzip", QStringList() << "-c");
if (!gzip.waitForStarted())
return false;
gzip.write("Qt rocks!");
if (!gzip.waitForFinished())
return false;
QByteArray result = gzip.readAll();

Notes for Windows Users

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

Symbian Platform Security Requirements

On Symbian, processes which use the functions kill() or terminate() must have the PowerMgmt platform security capability. If the client process lacks this capability, these functions will fail.

Platform security capabilities are added via the TARGET.CAPABILITY qmake variable.

See also
QBuffer, QFile, QTcpSocket

Definition at line 102 of file qprocess.h.

Enumerations

◆ ExitStatus

This enum describes the different exit statuses of QProcess.

  • NormalExit The process exited normally.
  • CrashExit The process crashed.
See also
exitStatus()
Enumerator
NormalExit 
CrashExit 

Definition at line 128 of file qprocess.h.

128  {
129  NormalExit,
130  CrashExit
131  };

◆ ProcessChannel

This enum describes the process channels used by the running process.

Pass one of these values to setReadChannel() to set the current read channel of QProcess.

  • StandardOutput The standard output (stdout) of the running process.
  • StandardError The standard error (stderr) of the running process.
See also
setReadChannel()
Enumerator
StandardOutput 
StandardError 

Definition at line 119 of file qprocess.h.

◆ ProcessChannelMode

This enum describes the process channel modes of QProcess.

Pass one of these values to setProcessChannelMode() to set the current read channel mode.

  • SeparateChannels QProcess manages the output of the running process, keeping standard output and standard error data in separate internal buffers. You can select the QProcess's current read channel by calling setReadChannel(). This is the default channel mode of QProcess.
  • MergedChannels 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.
  • ForwardedChannels 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()
Enumerator
SeparateChannels 
MergedChannels 
ForwardedChannels 

Definition at line 123 of file qprocess.h.

◆ ProcessError

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

  • FailedToStart The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.
  • Crashed The process crashed some time after starting successfully.
  • Timedout The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.
  • WriteError 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.
  • ReadError An error occurred when attempting to read from the process. For example, the process may not be running.
  • UnknownError An unknown error occurred. This is the default return value of error().
See also
error()
Enumerator
FailedToStart 
Crashed 
Timedout 
ReadError 
WriteError 
UnknownError 

Definition at line 106 of file qprocess.h.

106  {
107  FailedToStart, //### file not found, resource error
108  Crashed,
109  Timedout,
110  ReadError,
111  WriteError,
113  };

◆ ProcessState

This enum describes the different states of QProcess.

  • NotRunning The process is not running.
  • Starting The process is starting, but the program has not yet been invoked.
  • Running The process is running and is ready for reading and writing.
See also
state()
Enumerator
NotRunning 
Starting 
Running 

Definition at line 114 of file qprocess.h.

Constructors and Destructors

◆ QProcess()

QProcess::QProcess ( QObject parent = 0)
explicit

Constructs a QProcess object with the given parent.

Definition at line 1202 of file qprocess.cpp.

1203  : QIODevice(*new QProcessPrivate, parent)
1204 {
1205 #if defined QPROCESS_DEBUG
1206  qDebug("QProcess::QProcess(%p)", parent);
1207 #endif
1208 }
Q_CORE_EXPORT void qDebug(const char *,...)
QIODevice()
Constructs a QIODevice object.
Definition: qiodevice.cpp:390

◆ ~QProcess()

QProcess::~QProcess ( )
virtual

Destructs the QProcess object, i.e., killing the process.

Note that this function will not return until the process is terminated.

Definition at line 1216 of file qprocess.cpp.

1217 {
1218  Q_D(QProcess);
1219  if (d->processState != NotRunning) {
1220  qWarning("QProcess: Destroyed while process is still running.");
1221  kill();
1222  waitForFinished();
1223  }
1224 #ifdef Q_OS_UNIX
1225  // make sure the process manager removes this entry
1226  d->findExitCode();
1227 #endif
1228  d->cleanup();
1229 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool waitForFinished(int msecs=30000)
Blocks until the process has finished and the finished() signal has been emitted, or until msecs mill...
Definition: qprocess.cpp:1863
Q_CORE_EXPORT void qWarning(const char *,...)
void kill()
Kills the current process, causing it to exit immediately.
Definition: qprocess.cpp:2231
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

Functions

◆ atEnd()

bool QProcess::atEnd ( ) const
virtual

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

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1628 of file qprocess.cpp.

1629 {
1630  Q_D(const QProcess);
1631  const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1632  ? &d->errorReadBuffer
1633  : &d->outputReadBuffer;
1634  return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
1635 }
double d
Definition: qnumeric_p.h:62
bool isEmpty() const
#define Q_D(Class)
Definition: qglobal.h:2482
virtual bool atEnd() const
Returns true if the current read and write position is at the end of the device (i.e.
Definition: qiodevice.cpp:711
bool isOpen() const
Returns true if the device is open; otherwise returns false.
Definition: qiodevice.cpp:530
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ bytesAvailable()

qint64 QProcess::bytesAvailable ( ) const
virtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1646 of file qprocess.cpp.

1647 {
1648  Q_D(const QProcess);
1649  const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1650  ? &d->errorReadBuffer
1651  : &d->outputReadBuffer;
1652 #if defined QPROCESS_DEBUG
1653  qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
1654  (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
1655 #endif
1656  return readBuffer->size() + QIODevice::bytesAvailable();
1657 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
virtual qint64 bytesAvailable() const
Returns the number of bytes that are available for reading.
Definition: qiodevice.cpp:752
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102
int size() const

◆ bytesToWrite()

qint64 QProcess::bytesToWrite ( ) const
virtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1661 of file qprocess.cpp.

1662 {
1663  Q_D(const QProcess);
1664  qint64 size = d->writeBuffer.size();
1665 #ifdef Q_OS_WIN
1666  size += d->pipeWriterBytesToWrite();
1667 #endif
1668  return size;
1669 }
double d
Definition: qnumeric_p.h:62
virtual qint64 size() const
For open random-access devices, this function returns the size of the device.
Definition: qiodevice.cpp:642
#define Q_D(Class)
Definition: qglobal.h:2482
__int64 qint64
Definition: qglobal.h:942
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ canReadLine()

bool QProcess::canReadLine ( ) const
virtual

This function operates on the current read channel.

Reimplemented Function

See also
readChannel(), setReadChannel()

Reimplemented from QIODevice.

Definition at line 1596 of file qprocess.cpp.

1597 {
1598  Q_D(const QProcess);
1599  const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1600  ? &d->errorReadBuffer
1601  : &d->outputReadBuffer;
1602  return readBuffer->canReadLine() || QIODevice::canReadLine();
1603 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
bool canReadLine() const
virtual bool canReadLine() const
Returns true if a complete line of data can be read from the device; otherwise returns false...
Definition: qiodevice.cpp:1330
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ close()

void QProcess::close ( )
virtual

Closes all communication with the process and kills it.

After calling this function, QProcess will no longer emit readyRead(), and data can no longer be read or written.

Reimplemented from QIODevice.

Definition at line 1610 of file qprocess.cpp.

1611 {
1612  emit aboutToClose();
1613  while (waitForBytesWritten(-1))
1614  ;
1615  kill();
1616  waitForFinished(-1);
1617  QIODevice::close();
1618 }
virtual void close()
First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
Definition: qiodevice.cpp:590
void aboutToClose()
This signal is emitted when the device is about to close.
bool waitForFinished(int msecs=30000)
Blocks until the process has finished and the finished() signal has been emitted, or until msecs mill...
Definition: qprocess.cpp:1863
#define emit
Definition: qobjectdefs.h:76
void kill()
Kills the current process, causing it to exit immediately.
Definition: qprocess.cpp:2231
bool waitForBytesWritten(int msecs=30000)
Reimplemented Function
Definition: qprocess.cpp:1826

◆ closeReadChannel()

void QProcess::closeReadChannel ( ProcessChannel  channel)

Closes the read channel channel.

After calling this function, QProcess will no longer receive data on the channel. Any data that has already been received is still available for reading.

Call this function to save memory, if you are not interested in the output of the process.

See also
closeWriteChannel(), setReadChannel()

Definition at line 1343 of file qprocess.cpp.

1344 {
1345  Q_D(QProcess);
1346 
1347  if (channel == StandardOutput)
1348  d->stdoutChannel.closed = true;
1349  else
1350  d->stderrChannel.closed = true;
1351 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ closeWriteChannel()

void QProcess::closeWriteChannel ( )

Schedules the write channel of QProcess to be closed.

The channel will close once all data has been written to the process. After calling this function, any attempts to write to the process will fail.

Closing the write channel is necessary for programs that read input data until the channel has been closed. For example, the program "more" is used to display text data in a console on both Unix and Windows. But it will not display the text data until QProcess's write channel has been closed. Example:

QProcess more;
more.start("more");
more.write("Text to display");
// QProcess will emit readyRead() once "more" starts printing

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

See also
closeReadChannel()

Definition at line 1371 of file qprocess.cpp.

1372 {
1373  Q_D(QProcess);
1374  d->stdinChannel.closed = true; // closing
1375  if (d->writeBuffer.isEmpty())
1376  d->closeWriteChannel();
1377 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ environment()

QStringList QProcess::environment ( ) const

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

Note
The environment settings are ignored on Windows CE and Symbian, as there is no concept of an environment.
See also
processEnvironment(), setEnvironment(), systemEnvironment()

Definition at line 1731 of file qprocess.cpp.

Referenced by setProcessEnvironment().

1732 {
1733  Q_D(const QProcess);
1734  return d->environment.toStringList();
1735 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ error() [1/2]

QProcess::ProcessError QProcess::error ( ) const

Returns the type of error that occurred last.

See also
state()

Definition at line 1676 of file qprocess.cpp.

Referenced by start(), and writeData().

1677 {
1678  Q_D(const QProcess);
1679  return d->processError;
1680 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ error [2/2]

void QProcess::error ( QProcess::ProcessError  error)
signal

This signal is emitted when an error occurs with the process.

The specified error describes the type of error that occurred.

◆ execute() [1/2]

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

Starts the program program with the arguments arguments in a new process, waits for it to finish, and then returns the exit code of the process.

Any data the new process writes to the console is forwarded to the calling process.

The environment and working directory are inherited from the calling process.

On Windows, arguments that contain spaces are wrapped in quotes.

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

Definition at line 2279 of file qprocess.cpp.

2280 {
2281  QProcess process;
2283  process.start(program, arguments);
2284  if (!process.waitForFinished(-1))
2285  return -2;
2286  return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2287 }
int exitCode() const
Returns the exit code of the last process that finished.
Definition: qprocess.cpp:2240
bool waitForFinished(int msecs=30000)
Blocks until the process has finished and the finished() signal has been emitted, or until msecs mill...
Definition: qprocess.cpp:1863
QProcess::ExitStatus exitStatus() const
Returns the exit status of the last process that finished.
Definition: qprocess.cpp:2258
void setReadChannelMode(ProcessChannelMode mode)
Use setProcessChannelMode(mode) instead.
Definition: qprocess.cpp:1256
void start(const QString &program, const QStringList &arguments, OpenMode mode=ReadWrite)
Starts the given program in a new process, if none is already running, passing the command line argum...
Definition: qprocess.cpp:2060
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ execute() [2/2]

int QProcess::execute ( const QString program)
static

Starts the program program in a new process.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

Definition at line 2299 of file qprocess.cpp.

2300 {
2301  QProcess process;
2303  process.start(program);
2304  if (!process.waitForFinished(-1))
2305  return -2;
2306  return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2307 }
int exitCode() const
Returns the exit code of the last process that finished.
Definition: qprocess.cpp:2240
bool waitForFinished(int msecs=30000)
Blocks until the process has finished and the finished() signal has been emitted, or until msecs mill...
Definition: qprocess.cpp:1863
QProcess::ExitStatus exitStatus() const
Returns the exit status of the last process that finished.
Definition: qprocess.cpp:2258
void setReadChannelMode(ProcessChannelMode mode)
Use setProcessChannelMode(mode) instead.
Definition: qprocess.cpp:1256
void start(const QString &program, const QStringList &arguments, OpenMode mode=ReadWrite)
Starts the given program in a new process, if none is already running, passing the command line argum...
Definition: qprocess.cpp:2060
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ exitCode()

int QProcess::exitCode ( ) const

Returns the exit code of the last process that finished.

Definition at line 2240 of file qprocess.cpp.

Referenced by execute(), and QBenchmarkValgrindUtils::runCallgrindSubProcess().

2241 {
2242  Q_D(const QProcess);
2243  return d->exitCode;
2244 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ exitStatus()

QProcess::ExitStatus QProcess::exitStatus ( ) const

Returns the exit status of the last process that finished.

Since
4.1

On Windows, if the process was terminated with TerminateProcess() from another application this function will still return NormalExit unless the exit code is less than 0.

Definition at line 2258 of file qprocess.cpp.

Referenced by execute().

2259 {
2260  Q_D(const QProcess);
2261  return d->exitStatus;
2262 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ finished [1/2]

void QProcess::finished ( int  exitCode)
signal

◆ finished [2/2]

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

◆ isSequential()

bool QProcess::isSequential ( ) const
virtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1639 of file qprocess.cpp.

1640 {
1641  return true;
1642 }

◆ kill

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.

On Symbian, this function requires platform security capability PowerMgmt. If absent, the process will panic with KERN-EXEC 46.

Note
Killing running processes from other processes will typically cause a panic in Symbian due to platform security.
See also
{Symbian Platform Security Requirements}
terminate()

Definition at line 2231 of file qprocess.cpp.

Referenced by close(), and ~QProcess().

2232 {
2233  Q_D(QProcess);
2234  d->killProcess();
2235 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ nativeArguments()

QString QProcess::nativeArguments ( ) const

Returns the additional native command line arguments for the program.

Since
4.7
Note
This function is available only on the Windows and Symbian platforms.
See also
setNativeArguments()

Definition at line 1507 of file qprocess.cpp.

1508 {
1509  Q_D(const QProcess);
1510  return d->nativeArguments;
1511 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ pid()

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.

Definition at line 1581 of file qprocess.cpp.

Referenced by QBenchmarkValgrindUtils::runCallgrindSubProcess().

1582 {
1583  Q_D(const QProcess);
1584  return d->pid;
1585 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ processChannelMode()

QProcess::ProcessChannelMode QProcess::processChannelMode ( ) const

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

Since
4.2
See also
setProcessChannelMode(), ProcessChannelMode, setReadChannel()

Definition at line 1272 of file qprocess.cpp.

Referenced by readChannelMode().

1273 {
1274  Q_D(const QProcess);
1275  return d->processChannelMode;
1276 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ processEnvironment()

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

Since
4.6 If no environment has been set, the environment of the calling process will be used.
Note
The environment settings are ignored on Windows CE, as there is no concept of an environment.
See also
setProcessEnvironment(), setEnvironment(), QProcessEnvironment::isEmpty()

Definition at line 1775 of file qprocess.cpp.

1776 {
1777  Q_D(const QProcess);
1778  return d->environment;
1779 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ readAllStandardError()

QByteArray QProcess::readAllStandardError ( )

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

See also
readyReadStandardError(), readAllStandardOutput(), readChannel(), setReadChannel()

Definition at line 2029 of file qprocess.cpp.

Referenced by QBenchmarkValgrindUtils::runCallgrindSubProcess().

2030 {
2031  ProcessChannel tmp = readChannel();
2033  QByteArray data = readAll();
2034  setReadChannel(tmp);
2035  return data;
2036 }
ProcessChannel
This enum describes the process channels used by the running process.
Definition: qprocess.h:119
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const char * data(const QByteArray &arr)
void setReadChannel(ProcessChannel channel)
Sets the current read channel of the QProcess to the given channel.
Definition: qprocess.cpp:1317
ProcessChannel readChannel() const
Returns the current read channel of the QProcess.
Definition: qprocess.cpp:1303
QByteArray readAll()
Reads all available data from the device, and returns it as a QByteArray.
Definition: qiodevice.cpp:1025

◆ readAllStandardOutput()

QByteArray QProcess::readAllStandardOutput ( )

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

See also
readyReadStandardOutput(), readAllStandardError(), readChannel(), setReadChannel()

Definition at line 2013 of file qprocess.cpp.

Referenced by QBenchmarkValgrindUtils::haveValgrind(), and QBenchmarkValgrindUtils::runCallgrindSubProcess().

2014 {
2015  ProcessChannel tmp = readChannel();
2017  QByteArray data = readAll();
2018  setReadChannel(tmp);
2019  return data;
2020 }
ProcessChannel
This enum describes the process channels used by the running process.
Definition: qprocess.h:119
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
static const char * data(const QByteArray &arr)
void setReadChannel(ProcessChannel channel)
Sets the current read channel of the QProcess to the given channel.
Definition: qprocess.cpp:1317
ProcessChannel readChannel() const
Returns the current read channel of the QProcess.
Definition: qprocess.cpp:1303
QByteArray readAll()
Reads all available data from the device, and returns it as a QByteArray.
Definition: qiodevice.cpp:1025

◆ readChannel()

QProcess::ProcessChannel QProcess::readChannel ( ) const

Returns the current read channel of the QProcess.

See also
setReadChannel()

Definition at line 1303 of file qprocess.cpp.

Referenced by readAllStandardError(), and readAllStandardOutput().

1304 {
1305  Q_D(const QProcess);
1306  return d->processChannel;
1307 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ readChannelMode()

QProcess::ProcessChannelMode QProcess::readChannelMode ( ) const

Returns the read channel mode of the QProcess.

See also
processChannelMode()

Definition at line 1241 of file qprocess.cpp.

1242 {
1243  return processChannelMode();
1244 }
ProcessChannelMode processChannelMode() const
Returns the channel mode of the QProcess standard output and standard error channels.
Definition: qprocess.cpp:1272

◆ readData()

qint64 QProcess::readData ( char *  data,
qint64  maxlen 
)
protectedvirtual

Reimplemented Function

Implements QIODevice.

Definition at line 1917 of file qprocess.cpp.

1918 {
1919  Q_D(QProcess);
1920  QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
1921  ? &d->errorReadBuffer
1922  : &d->outputReadBuffer;
1923 
1924  if (maxlen == 1 && !readBuffer->isEmpty()) {
1925  int c = readBuffer->getChar();
1926  if (c == -1) {
1927 #if defined QPROCESS_DEBUG
1928  qDebug("QProcess::readData(%p \"%s\", %d) == -1",
1929  data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1930 #endif
1931  return -1;
1932  }
1933  *data = (char) c;
1934 #if defined QPROCESS_DEBUG
1935  qDebug("QProcess::readData(%p \"%s\", %d) == 1",
1936  data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
1937 #endif
1938  return 1;
1939  }
1940 
1941  qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
1942  qint64 readSoFar = 0;
1943  while (readSoFar < bytesToRead) {
1944  const char *ptr = readBuffer->readPointer();
1945  int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
1946  readBuffer->nextDataBlockSize());
1947  memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
1948  readSoFar += bytesToReadFromThisBlock;
1949  readBuffer->free(bytesToReadFromThisBlock);
1950  }
1951 
1952 #if defined QPROCESS_DEBUG
1953  qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
1954  data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
1955 #endif
1956  if (!readSoFar && d->processState == QProcess::NotRunning)
1957  return -1; // EOF
1958  return readSoFar;
1959 }
double d
Definition: qnumeric_p.h:62
unsigned char c[8]
Definition: qnumeric_p.h:62
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
const char * readPointer() const
Definition: qringbuffer_p.h:73
int nextDataBlockSize() const
Definition: qringbuffer_p.h:69
bool isEmpty() const
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
static const char * data(const QByteArray &arr)
const T * ptr(const T &t)
__int64 qint64
Definition: qglobal.h:942
void free(int bytes)
if(void) toggleToolbarShown
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102
int size() const

◆ readyReadStandardError

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

◆ readyReadStandardOutput

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

◆ setEnvironment()

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(QRegExp("^PATH=(.*)", Qt::CaseInsensitive), "PATH=\\1;C:\\Bin");
process.setEnvironment(env);
process.start("myapp");
Note
This function is less efficient than the setProcessEnvironment() function.
See also
environment(), setProcessEnvironment(), systemEnvironment()

Definition at line 1711 of file qprocess.cpp.

1712 {
1714 }
static QProcessEnvironment fromList(const QStringList &list)
Definition: qprocess.cpp:167
void setProcessEnvironment(const QProcessEnvironment &environment)
Sets the environment that QProcess will use when starting a process to the environment object...
Definition: qprocess.cpp:1754

◆ setNativeArguments()

void QProcess::setNativeArguments ( const QString arguments)

Sets additional native command line arguments for the program.

Since
4.7 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

On operating systems where the system API for passing command line arguments to a subprocess natively uses a single string, one can conceive command lines which cannot be passed via QProcess's portable list-based API. In such cases this function must be used to set a string which is appended to the string composed from the usual argument list, with a delimiting space.

Note
This function is available only on the Windows and Symbian platforms.
See also
nativeArguments()

Definition at line 1534 of file qprocess.cpp.

1535 {
1536  Q_D(QProcess);
1537  d->nativeArguments = arguments;
1538 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setProcessChannelMode()

void QProcess::setProcessChannelMode ( ProcessChannelMode  mode)

Sets the channel mode of the QProcess standard output and standard error channels to the mode specified.

Since
4.2

This mode will be used the next time start() is called. For example:

QProcess builder;
builder.start("make", QStringList() << "-j2");
if (!builder.waitForFinished())
qDebug() << "Make failed:" << builder.errorString();
else
qDebug() << "Make output:" << builder.readAll();
See also
processChannelMode(), ProcessChannelMode, setReadChannel()

Definition at line 1292 of file qprocess.cpp.

Referenced by setReadChannelMode().

1293 {
1294  Q_D(QProcess);
1295  d->processChannelMode = mode;
1296 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setProcessEnvironment()

void QProcess::setProcessEnvironment ( const QProcessEnvironment environment)

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

Since
4.6

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");

Note how, on Windows, environment variable names are case-insensitive.

See also
processEnvironment(), QProcessEnvironment::systemEnvironment(), setEnvironment()

Definition at line 1754 of file qprocess.cpp.

Referenced by setEnvironment().

1755 {
1756  Q_D(QProcess);
1757  d->environment = environment;
1758 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
QStringList environment() const
Returns the environment that QProcess will use when starting a process, or an empty QStringList if no...
Definition: qprocess.cpp:1731
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setProcessState()

void QProcess::setProcessState ( ProcessState  state)
protected

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

See also
state()

Definition at line 1886 of file qprocess.cpp.

1887 {
1888  Q_D(QProcess);
1889  if (d->processState == state)
1890  return;
1891  d->processState = state;
1893 }
double d
Definition: qnumeric_p.h:62
QProcess::ProcessState state() const
Returns the current state of the process.
Definition: qprocess.cpp:1687
#define Q_D(Class)
Definition: qglobal.h:2482
#define emit
Definition: qobjectdefs.h:76
void stateChanged(QProcess::ProcessState state)
This signal is emitted whenever the state of QProcess changes.
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setReadChannel()

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

Definition at line 1317 of file qprocess.cpp.

Referenced by readAllStandardError(), and readAllStandardOutput().

1318 {
1319  Q_D(QProcess);
1320  if (d->processChannel != channel) {
1321  QByteArray buf = d->buffer.readAll();
1322  if (d->processChannel == QProcess::StandardOutput) {
1323  for (int i = buf.size() - 1; i >= 0; --i)
1324  d->outputReadBuffer.ungetChar(buf.at(i));
1325  } else {
1326  for (int i = buf.size() - 1; i >= 0; --i)
1327  d->errorReadBuffer.ungetChar(buf.at(i));
1328  }
1329  }
1330  d->processChannel = channel;
1331 }
double d
Definition: qnumeric_p.h:62
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define Q_D(Class)
Definition: qglobal.h:2482
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
char at(int i) const
Returns the character at index position i in the byte array.
Definition: qbytearray.h:413
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setReadChannelMode()

void QProcess::setReadChannelMode ( ProcessChannelMode  mode)

Use setProcessChannelMode(mode) instead.

See also
setProcessChannelMode()

Definition at line 1256 of file qprocess.cpp.

Referenced by execute().

1257 {
1258  setProcessChannelMode(mode);
1259 }
void setProcessChannelMode(ProcessChannelMode mode)
Sets the channel mode of the QProcess standard output and standard error channels to the mode specifi...
Definition: qprocess.cpp:1292

◆ setStandardErrorFile()

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

Redirects the process' standard error to the file fileName.

Since
4.2

When the redirection is in place, the standard error read channel is closed: reading from it using read() will always fail, as will readAllStandardError(). The file will be appended to if mode is Append, otherwise, it will be truncated.

See setStandardOutputFile() for more information on how the file is opened.

Note: if setProcessChannelMode() was called with an argument of QProcess::MergedChannels, this function has no effect.

See also
setStandardInputFile(), setStandardOutputFile(), setStandardOutputProcess()

Definition at line 1460 of file qprocess.cpp.

1461 {
1462  Q_ASSERT(mode == Append || mode == Truncate);
1463  Q_D(QProcess);
1464 
1465  d->stderrChannel = fileName;
1466  d->stderrChannel.append = mode == Append;
1467 }
double d
Definition: qnumeric_p.h:62
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
#define Q_D(Class)
Definition: qglobal.h:2482
static QString fileName(const QString &fileUrl)
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setStandardInputFile()

void QProcess::setStandardInputFile ( const QString fileName)

Redirects the process' standard input to the file indicated by fileName.

Since
4.2

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

Definition at line 1399 of file qprocess.cpp.

1400 {
1401  Q_D(QProcess);
1402  d->stdinChannel = fileName;
1403 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
static QString fileName(const QString &fileUrl)
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setStandardOutputFile()

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

Redirects the process' standard output to the file fileName.

Since
4.2

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 doesn't exist at the moment start() is called, it will be created. If it cannot be created, the starting will fail.

If the file exists and mode is QIODevice::Truncate, the file will be truncated. Otherwise (if mode is QIODevice::Append), the file will be appended to.

Calling setStandardOutputFile() after the process has started has no effect.

See also
setStandardInputFile(), setStandardErrorFile(), setStandardOutputProcess()

Definition at line 1430 of file qprocess.cpp.

1431 {
1432  Q_ASSERT(mode == Append || mode == Truncate);
1433  Q_D(QProcess);
1434 
1435  d->stdoutChannel = fileName;
1436  d->stdoutChannel.append = mode == Append;
1437 }
double d
Definition: qnumeric_p.h:62
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
#define Q_D(Class)
Definition: qglobal.h:2482
static QString fileName(const QString &fileUrl)
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ setStandardOutputProcess()

void QProcess::setStandardOutputProcess ( QProcess destination)

Pipes the standard output stream of this process to the destination process' standard input.

Since
4.2

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");

Definition at line 1484 of file qprocess.cpp.

1485 {
1486  QProcessPrivate *dfrom = d_func();
1487  QProcessPrivate *dto = destination->d_func();
1488  dfrom->stdoutChannel.pipeTo(dto);
1489  dto->stdinChannel.pipeFrom(dfrom);
1490 }
void pipeFrom(QProcessPrivate *other)
Definition: qprocess_p.h:277
void pipeTo(QProcessPrivate *other)
Definition: qprocess_p.h:270
Channel stdinChannel
Definition: qprocess_p.h:317
Channel stdoutChannel
Definition: qprocess_p.h:318

◆ setupChildProcess()

void QProcess::setupChildProcess ( )
protectedvirtual

This function is called in the child process context just before the program is executed on Unix or Mac OS X (i.e., after fork(), but before execve()).

Reimplement this function to do last minute initialization of the child process. Example:

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 cannot exit the process (by calling exit(), for instance) from this function. If you need to stop the program before it starts execution, your workaround is to emit finished() and then call exit().

Warning
This function is called by QProcess on Unix and Mac OS X only. On Windows and QNX, it is not called.

Definition at line 1911 of file qprocess.cpp.

1912 {
1913 }

◆ setWorkingDirectory()

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.

Note
The working directory setting is ignored on Symbian; the private directory of the process is considered its working directory.
On QNX, this may cause all application threads to temporarily freeze.
See also
workingDirectory(), start()

Definition at line 1571 of file qprocess.cpp.

1572 {
1573  Q_D(QProcess);
1574  d->workingDirectory = dir;
1575 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ start() [1/2]

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

Starts the given program in a new process, if none is already running, passing the command line arguments in arguments.

The OpenMode is set to mode.

The QProcess object will immediately enter the Starting state. If the process starts successfully, QProcess will emit started(); otherwise, error() will be 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.

Note
Processes are started asynchronously, which means the started() and error() signals may be delayed. Call waitForStarted() to make sure the process has started (or has failed to start) and those signals have been emitted.
No further splitting of the arguments is performed.

Windows: Arguments that contain spaces are wrapped in quotes.

See also
pid(), started(), waitForStarted()

Definition at line 2060 of file qprocess.cpp.

Referenced by execute(), QBenchmarkValgrindUtils::haveValgrind(), QBenchmarkValgrindUtils::runCallgrindSubProcess(), and start().

2061 {
2062  Q_D(QProcess);
2063  if (d->processState != NotRunning) {
2064  qWarning("QProcess::start: Process is already running");
2065  return;
2066  }
2067 
2068 #if defined QPROCESS_DEBUG
2069  qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')';
2070 #endif
2071 
2072  d->outputReadBuffer.clear();
2073  d->errorReadBuffer.clear();
2074 
2075  if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
2076  mode &= ~WriteOnly; // not open for writing
2077  if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
2078  (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
2079  d->processChannelMode == MergedChannels))
2080  mode &= ~ReadOnly; // not open for reading
2081  if (mode == 0)
2082  mode = Unbuffered;
2083  QIODevice::open(mode);
2084 
2085  d->stdinChannel.closed = false;
2086  d->stdoutChannel.closed = false;
2087  d->stderrChannel.closed = false;
2088 
2089  d->program = program;
2090  d->arguments = arguments;
2091 
2092  d->exitCode = 0;
2093  d->exitStatus = NormalExit;
2094  d->processError = QProcess::UnknownError;
2095  d->errorString.clear();
2096  d->startProcess();
2097 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
Q_CORE_EXPORT void qWarning(const char *,...)
virtual bool open(OpenMode mode)
Opens the device and sets its OpenMode to mode.
Definition: qiodevice.cpp:570
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ start() [2/2]

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

Starts the program program in a new process, if one is not already running.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces. For example:

QProcess process;
process.start("del /s *.txt");
// same as process.start("del", QStringList() << "/s" << "*.txt");
...

The program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process. For example:

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

If the QProcess object is already running a process, a warning may be printed at the console, and the existing process will continue running.

Note that, on Windows, quotes need to be both escaped and quoted. For example, the above code would be specified in the following way to ensure that "My Documents" is used as the argument to the dir executable:

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

The OpenMode is set to mode.

Definition at line 2170 of file qprocess.cpp.

2171 {
2172  QStringList args = parseCombinedArgString(program);
2173  if (args.isEmpty()) {
2174  Q_D(QProcess);
2175  d->processError = QProcess::FailedToStart;
2176  setErrorString(tr("No program defined"));
2177  emit error(d->processError);
2178  return;
2179  }
2180 
2181  QString prog = args.first();
2182  args.removeFirst();
2183 
2184  start(prog, args, mode);
2185 }
double d
Definition: qnumeric_p.h:62
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
#define emit
Definition: qobjectdefs.h:76
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
void removeFirst()
Removes the first item in the list.
Definition: qlist.h:286
QProcess::ProcessError error() const
Returns the type of error that occurred last.
Definition: qprocess.cpp:1676
T & first()
Returns a reference to the first item in the list.
Definition: qlist.h:282
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
void start(const QString &program, const QStringList &arguments, OpenMode mode=ReadWrite)
Starts the given program in a new process, if none is already running, passing the command line argum...
Definition: qprocess.cpp:2060
static QStringList parseCombinedArgString(const QString &program)
Definition: qprocess.cpp:2100
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ startDetached() [1/3]

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

Starts the program program with the arguments arguments in a new process, and detaches from it.

Returns true on success; otherwise returns false. If the calling process exits, the detached process will continue to live.

Note that arguments that 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.

Note
On QNX, this may cause all application threads to temporarily freeze.

If the function is successful then *pid is set to the process identifier of the started process.

Definition at line 2332 of file qprocess.cpp.

Referenced by launch(), and openDocument().

2336 {
2337  return QProcessPrivate::startDetached(program,
2338  arguments,
2339  workingDirectory,
2340  pid);
2341 }
static bool startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory=QString(), qint64 *pid=0)
Q_PID pid() const
Returns the native process identifier for the running process, if available.
Definition: qprocess.cpp:1581

◆ startDetached() [2/3]

bool QProcess::startDetached ( const QString program,
const QStringList arguments 
)
static

Starts the program program with the given 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.

Note
Arguments that 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.

Definition at line 2358 of file qprocess.cpp.

2360 {
2361  return QProcessPrivate::startDetached(program, arguments);
2362 }
static bool startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory=QString(), qint64 *pid=0)

◆ startDetached() [3/3]

bool QProcess::startDetached ( const QString program)
static

Starts the program program in a new process.

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

program is a single string of text containing both the program name and its arguments. The arguments are separated by one or more spaces.

The program string can also contain quotes, to ensure that arguments containing spaces are correctly supplied to the new process.

Definition at line 2377 of file qprocess.cpp.

2378 {
2379  QStringList args = parseCombinedArgString(program);
2380  if (args.isEmpty())
2381  return false;
2382 
2383  QString prog = args.first();
2384  args.removeFirst();
2385 
2386  return QProcessPrivate::startDetached(prog, args);
2387 }
static bool startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory=QString(), qint64 *pid=0)
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
void removeFirst()
Removes the first item in the list.
Definition: qlist.h:286
T & first()
Returns a reference to the first item in the list.
Definition: qlist.h:282
static QStringList parseCombinedArgString(const QString &program)
Definition: qprocess.cpp:2100

◆ started

void QProcess::started ( )
signal

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

Referenced by waitForBytesWritten(), and waitForFinished().

◆ state()

QProcess::ProcessState QProcess::state ( ) const

Returns the current state of the process.

See also
stateChanged(), error()

Definition at line 1687 of file qprocess.cpp.

Referenced by setProcessState().

1688 {
1689  Q_D(const QProcess);
1690  return d->processState;
1691 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ stateChanged

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.

Referenced by setProcessState().

◆ systemEnvironment()

QStringList QProcess::systemEnvironment ( )
static

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

Since
4.1

Example:

// environment = {"PATH=/usr/bin:/usr/local/bin",
// "USER=greg", "HOME=/home/greg"}

This function does not cache the system environment. Therefore, it's possible to obtain an updated version of the environment if low-level C library functions like setenv ot putenv have been called.

However, note that repeated calls to this function will recreate the list of environment variables, which is a non-trivial operation.

Note
For new code, it is recommended to use QProcessEnvironment::systemEnvironment()
See also
QProcessEnvironment::systemEnvironment(), environment(), setEnvironment()

Definition at line 2423 of file qprocess.cpp.

2424 {
2425  QStringList tmp;
2426  char *entry = 0;
2427  int count = 0;
2428  while ((entry = environ[count++]))
2429  tmp << QString::fromLocal8Bit(entry);
2430  return tmp;
2431 }
static QString fromLocal8Bit(const char *, int size=-1)
Returns a QString initialized with the first size characters of the 8-bit string str.
Definition: qstring.cpp:4245
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
#define environ
Definition: qprocess.cpp:2392

◆ terminate

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

On Symbian, this function requires platform security capability PowerMgmt. If absent, the process will panic with KERN-EXEC 46.

Note
Terminating running processes from other processes will typically cause a panic in Symbian due to platform security.
See also
{Symbian Platform Security Requirements}
kill()

Definition at line 2210 of file qprocess.cpp.

2211 {
2212  Q_D(QProcess);
2213  d->terminateProcess();
2214 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ waitForBytesWritten()

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

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1826 of file qprocess.cpp.

Referenced by close().

1827 {
1828  Q_D(QProcess);
1829  if (d->processState == QProcess::NotRunning)
1830  return false;
1831  if (d->processState == QProcess::Starting) {
1832  QElapsedTimer stopWatch;
1833  stopWatch.start();
1834  bool started = waitForStarted(msecs);
1835  if (!started)
1836  return false;
1837  if (msecs != -1)
1838  msecs -= stopWatch.elapsed();
1839  }
1840 
1841  return d->waitForBytesWritten(msecs);
1842 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
void started()
This signal is emitted by QProcess when the process has started, and state() returns Running ...
bool waitForStarted(int msecs=30000)
Blocks until the process has started and the started() signal has been emitted, or until msecs millis...
Definition: qprocess.cpp:1800
void start()
Starts this timer.
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ waitForFinished()

bool QProcess::waitForFinished ( int  msecs = 30000)

Blocks until the process has finished and the finished() signal has been emitted, or until msecs milliseconds have passed.

Returns true if the process finished; otherwise returns false (if the operation timed out, if an error occurred, or if this QProcess is already finished).

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

Warning
Calling this function from the main (GUI) thread might cause your user interface to freeze.

If msecs is -1, this function will not time out.

See also
finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()

Definition at line 1863 of file qprocess.cpp.

Referenced by close(), execute(), QBenchmarkValgrindUtils::haveValgrind(), QBenchmarkValgrindUtils::runCallgrindSubProcess(), and ~QProcess().

1864 {
1865  Q_D(QProcess);
1866  if (d->processState == QProcess::NotRunning)
1867  return false;
1868  if (d->processState == QProcess::Starting) {
1869  QElapsedTimer stopWatch;
1870  stopWatch.start();
1871  bool started = waitForStarted(msecs);
1872  if (!started)
1873  return false;
1874  if (msecs != -1)
1875  msecs -= stopWatch.elapsed();
1876  }
1877 
1878  return d->waitForFinished(msecs);
1879 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
void started()
This signal is emitted by QProcess when the process has started, and state() returns Running ...
bool waitForStarted(int msecs=30000)
Blocks until the process has started and the started() signal has been emitted, or until msecs millis...
Definition: qprocess.cpp:1800
void start()
Starts this timer.
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ waitForReadyRead()

bool QProcess::waitForReadyRead ( int  msecs = 30000)
virtual

Reimplemented Function

Reimplemented from QIODevice.

Definition at line 1811 of file qprocess.cpp.

1812 {
1813  Q_D(QProcess);
1814 
1815  if (d->processState == QProcess::NotRunning)
1816  return false;
1817  if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
1818  return false;
1819  if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
1820  return false;
1821  return d->waitForReadyRead(msecs);
1822 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ waitForStarted()

bool QProcess::waitForStarted ( int  msecs = 30000)

Blocks until the process has started and the started() signal has been emitted, or until msecs milliseconds have passed.

Returns true if the process was started successfully; otherwise returns false (if the operation timed out or if an error occurred).

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

Warning
Calling this function from the main (GUI) thread might cause your user interface to freeze.

If msecs is -1, this function will not time out.

See also
started(), waitForReadyRead(), waitForBytesWritten(), waitForFinished()

Definition at line 1800 of file qprocess.cpp.

Referenced by QBenchmarkValgrindUtils::runCallgrindSubProcess(), waitForBytesWritten(), and waitForFinished().

1801 {
1802  Q_D(QProcess);
1803  if (d->processState == QProcess::Starting)
1804  return d->waitForStarted(msecs);
1805 
1806  return d->processState == QProcess::Running;
1807 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ workingDirectory()

QString QProcess::workingDirectory ( ) const

If QProcess has been assigned a working directory, this function returns the working directory that the QProcess will enter before the program has started.

Otherwise, (i.e., no directory has been assigned,) an empty string is returned, and QProcess will use the application's current working directory instead.

See also
setWorkingDirectory()

Definition at line 1551 of file qprocess.cpp.

1552 {
1553  Q_D(const QProcess);
1554  return d->workingDirectory;
1555 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

◆ writeData()

qint64 QProcess::writeData ( const char *  data,
qint64  len 
)
protectedvirtual

Reimplemented Function

Implements QIODevice.

Definition at line 1963 of file qprocess.cpp.

1964 {
1965  Q_D(QProcess);
1966 
1967 #if defined(Q_OS_WINCE)
1968  Q_UNUSED(data);
1969  Q_UNUSED(len);
1970  d->processError = QProcess::WriteError;
1971  setErrorString(tr("Error writing to process"));
1972  emit error(d->processError);
1973  return -1;
1974 #endif
1975 
1976  if (d->stdinChannel.closed) {
1977 #if defined QPROCESS_DEBUG
1978  qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
1979  data, qt_prettyDebug(data, len, 16).constData(), len);
1980 #endif
1981  return 0;
1982  }
1983 
1984  if (len == 1) {
1985  d->writeBuffer.putChar(*data);
1986  if (d->stdinChannel.notifier)
1987  d->stdinChannel.notifier->setEnabled(true);
1988 #if defined QPROCESS_DEBUG
1989  qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
1990  data, qt_prettyDebug(data, len, 16).constData(), len);
1991 #endif
1992  return 1;
1993  }
1994 
1995  char *dest = d->writeBuffer.reserve(len);
1996  memcpy(dest, data, len);
1997  if (d->stdinChannel.notifier)
1998  d->stdinChannel.notifier->setEnabled(true);
1999 #if defined QPROCESS_DEBUG
2000  qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
2001  data, qt_prettyDebug(data, len, 16).constData(), len, len);
2002 #endif
2003  return len;
2004 }
double d
Definition: qnumeric_p.h:62
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qDebug(const char *,...)
#define emit
Definition: qobjectdefs.h:76
static const char * data(const QByteArray &arr)
QProcess::ProcessError error() const
Returns the type of error that occurred last.
Definition: qprocess.cpp:1676
void setErrorString(const QString &errorString)
Sets the human readable description of the last device error that occurred to str.
Definition: qiodevice.cpp:1660
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
The QProcess class is used to start external programs and to communicate with them.
Definition: qprocess.h:102

Friends and Related Functions

◆ Q_PID()

Q_PID
related

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

See also
QProcess::pid()

◆ QProcessManager

friend class QProcessManager
friend

Definition at line 236 of file qprocess.h.


The documentation for this class was generated from the following files: