QProcess Class Reference

#include <qprocess.h>

Inheritance diagram for QProcess:

Inheritance graph
[legend]
Collaboration diagram for QProcess:

Collaboration graph
[legend]
List of all members.

Detailed Description

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

To start a process, pass the name and command line arguments of the program you want to run as arguments to start(). For example:

snippets/qprocess/qprocess-simpleexecution.cpp parent parent program program QStringList start

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.

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.

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.

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

waitForStarted() blocks until the process has started.

waitForReadyRead() blocks until new data is available for reading on the current read channel.

waitForBytesWritten() blocks until one payload of data has been written to the process.

waitForFinished() blocks until the process has finished.

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

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

snippets/process/process.cpp QProcess gzip; result = gzip.readAll();

See also:
QBuffer, QFile, QTcpSocket

Definition at line 44 of file qprocess.h.

Public Types

enum  ProcessError
enum  ProcessState
enum  ProcessChannel
enum  ProcessChannelMode
enum  ExitStatus

Public Slots

void terminate ()
void kill ()

Signals

void started ()
void finished (int exitCode)
void finished (int exitCode, QProcess::ExitStatus exitStatus)
void error (QProcess::ProcessError error)
void stateChanged (QProcess::ProcessState state)
void readyReadStandardOutput ()
void readyReadStandardError ()

Public Member Functions

 QProcess (QObject *parent=0)
virtual ~QProcess ()
void start (const QString &program, const QStringList &arguments, OpenMode mode=ReadWrite)
void start (const QString &program, OpenMode mode=ReadWrite)
ProcessChannelMode readChannelMode () const
void setReadChannelMode (ProcessChannelMode mode)
ProcessChannelMode processChannelMode () const
void setProcessChannelMode (ProcessChannelMode mode)
ProcessChannel readChannel () const
void setReadChannel (ProcessChannel channel)
void closeReadChannel (ProcessChannel channel)
void closeWriteChannel ()
void setStandardInputFile (const QString &fileName)
void setStandardOutputFile (const QString &fileName, OpenMode mode=Truncate)
void setStandardErrorFile (const QString &fileName, OpenMode mode=Truncate)
void setStandardOutputProcess (QProcess *destination)
QString workingDirectory () const
void setWorkingDirectory (const QString &dir)
void setEnvironment (const QStringList &environment)
QStringList environment () const
QProcess::ProcessError error () const
QProcess::ProcessState state () const
Q_PID pid () const
bool waitForStarted (int msecs=30000)
bool waitForReadyRead (int msecs=30000)
bool waitForBytesWritten (int msecs=30000)
bool waitForFinished (int msecs=30000)
QByteArray readAllStandardOutput ()
QByteArray readAllStandardError ()
int exitCode () const
QProcess::ExitStatus exitStatus () const
qint64 bytesAvailable () const
qint64 bytesToWrite () const
bool isSequential () const
bool canReadLine () const
void close ()
bool atEnd () const

Static Public Member Functions

static int execute (const QString &program, const QStringList &arguments)
static int execute (const QString &program)
static bool startDetached (const QString &program, const QStringList &arguments)
static bool startDetached (const QString &program)
static QStringList systemEnvironment ()

Protected Member Functions

void setProcessState (ProcessState state)
virtual void setupChildProcess ()
qint64 readData (char *data, qint64 maxlen)
qint64 writeData (const char *data, qint64 len)

Private Member Functions

 Q_PRIVATE_SLOT (d_func(), bool _q_canReadStandardOutput()) Q_PRIVATE_SLOT(d_func()
bool _q_canReadStandardError ()) Q_PRIVATE_SLOT(d_func()
bool bool _q_canWrite ()) Q_PRIVATE_SLOT(d_func()
bool bool bool _q_startupNotification ()) Q_PRIVATE_SLOT(d_func()
bool bool bool bool _q_processDied ()) Q_PRIVATE_SLOT(d_func()
bool bool bool bool void _q_notified ()) friend class QProcessManager

Related Functions

(Note that these are not member functions.)

 Q_PID


Member Enumeration Documentation

enum QProcess::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()

Definition at line 48 of file qprocess.h.

00048                       {
00049         FailedToStart, //### file not found, resource error
00050         Crashed,
00051         Timedout,
00052         ReadError,
00053         WriteError,
00054         UnknownError
00055     };

enum QProcess::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()

Definition at line 56 of file qprocess.h.

00056                       {
00057         NotRunning,
00058         Starting,
00059         Running
00060     };

enum QProcess::ProcessChannel

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

StandardOutput The standard output (stdout) of the running process.

StandardError The standard error (stderr) of the running process.

See also:
setReadChannel()

Definition at line 61 of file qprocess.h.

00061                         {
00062         StandardOutput,
00063         StandardError
00064     };

enum QProcess::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:
setReadChannelMode()

Definition at line 65 of file qprocess.h.

00065                             {
00066         SeparateChannels,
00067         MergedChannels,
00068         ForwardedChannels
00069     };

enum QProcess::ExitStatus

This enum describes the different exit statuses of QProcess.

NormalExit The process exited normally.

CrashExit The process crashed.

See also:
exitStatus()

Definition at line 70 of file qprocess.h.

00070                     {
00071         NormalExit,
00072         CrashExit
00073     };


Constructor & Destructor Documentation

QProcess::QProcess ( QObject parent = 0  )  [explicit]

Constructs a QProcess object with the given parent.

Definition at line 703 of file qprocess.cpp.

References QObject::parent(), and qDebug().

00704     : QIODevice(*new QProcessPrivate, parent)
00705 {
00706 #if defined QPROCESS_DEBUG
00707     qDebug("QProcess::QProcess(%p)", parent);
00708 #endif
00709 }

Here is the call graph for this function:

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 717 of file qprocess.cpp.

References d, kill(), NotRunning, qWarning(), and waitForFinished().

00718 {
00719     Q_D(QProcess);
00720     if (d->processState != NotRunning) {
00721         qWarning("QProcess: Destroyed while process is still running.");
00722         kill();
00723         waitForFinished();
00724     }
00725 #ifdef Q_OS_UNIX
00726     // make sure the process manager removes this entry
00727     d->findExitCode();
00728 #endif
00729     d->cleanup();
00730 }

Here is the call graph for this function:


Member Function Documentation

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

Starts the program program in a new process, passing the command line arguments in arguments. The OpenMode is set to mode. QProcess will immediately enter the Starting state. If the process starts successfully, QProcess will emit started(); otherwise, error() will be emitted.

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

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.

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

Definition at line 1431 of file qprocess.cpp.

References d, MergedChannels, QProcessPrivate::Channel::Normal, NormalExit, NotRunning, qDebug(), qWarning(), QIODevice::ReadOnly, QIODevice::setOpenMode(), QIODevice::Unbuffered, UnknownError, and QIODevice::WriteOnly.

Referenced by qdesigner_internal::QDesignerResource::create(), execute(), Launcher::launchExample(), QCleanlooksStylePrivate::lookupIconTheme(), main(), QAssistantClient::openAssistant(), and start().

01432 {
01433     Q_D(QProcess);
01434     if (d->processState != NotRunning) {
01435         qWarning("QProcess::start: Process is already running");
01436         return;
01437     }
01438 
01439 #if defined QPROCESS_DEBUG
01440     qDebug() << "QProcess::start(" << program << "," << arguments << "," << mode << ")";
01441 #endif
01442 
01443     d->outputReadBuffer.clear();
01444     d->errorReadBuffer.clear();
01445 
01446     if (d->stdinChannel.type != QProcessPrivate::Channel::Normal)
01447         mode &= ~WriteOnly;     // not open for writing
01448     if (d->stdoutChannel.type != QProcessPrivate::Channel::Normal &&
01449         (d->stderrChannel.type != QProcessPrivate::Channel::Normal ||
01450          d->processChannelMode == MergedChannels))
01451         mode &= ~ReadOnly;      // not open for reading
01452     if (mode == 0)
01453         mode = Unbuffered;
01454     setOpenMode(mode);
01455 
01456     d->stdinChannel.closed = false;
01457     d->stdoutChannel.closed = false;
01458     d->stderrChannel.closed = false;
01459 
01460     d->program = program;
01461     d->arguments = arguments;
01462 
01463     d->exitCode = 0;
01464     d->exitStatus = NormalExit;
01465     d->processError = QProcess::UnknownError;
01466     d->errorString.clear();
01467     d->startProcess();
01468 }

Here is the call graph for this function:

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Starts the program program in a new process. 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\"");

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 1546 of file qprocess.cpp.

References QList< T >::first(), parseCombinedArgString(), QList< T >::removeFirst(), and start().

01547 {
01548     QStringList args = parseCombinedArgString(program);
01549 
01550     QString prog = args.first();
01551     args.removeFirst();
01552 
01553     start(prog, args, mode);
01554 }

Here is the call graph for this function:

QProcess::ProcessChannelMode QProcess::readChannelMode (  )  const

Returns the read channel mode of the QProcess. This function is equivalent to processChannelMode()

See also:
processChannelMode()

Definition at line 739 of file qprocess.cpp.

References processChannelMode().

00740 {
00741     return processChannelMode();
00742 }

Here is the call graph for this function:

void QProcess::setReadChannelMode ( ProcessChannelMode  mode  ) 

Use setProcessChannelMode(mode) instead.

See also:
setProcessChannelMode()

Definition at line 751 of file qprocess.cpp.

References setProcessChannelMode().

Referenced by execute().

00752 {
00753     setProcessChannelMode(mode);
00754 }

Here is the call graph for this function:

QProcess::ProcessChannelMode QProcess::processChannelMode (  )  const

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

See also:
setReadChannelMode(), ProcessChannelMode, setReadChannel()

Definition at line 764 of file qprocess.cpp.

References d.

Referenced by readChannelMode().

00765 {
00766     Q_D(const QProcess);
00767     return d->processChannelMode;
00768 }

void QProcess::setProcessChannelMode ( ProcessChannelMode  mode  ) 

Since:
4.2
Sets the channel mode of the QProcess standard output and standard error channels to the mode specified. This mode will be used the next time start() is called. For example:

        QProcess builder;
        builder.setProcessChannelMode(QProcess::MergedChannels);
        builder.start("make", QStringList() << "-j2");

        if (!builder.waitForFinished())
            qDebug() << "Make failed:" << builder.errorString();
        else
            qDebug() << "Make output:" << builder.readAll();

See also:
readChannelMode(), ProcessChannelMode, setReadChannel()

Definition at line 790 of file qprocess.cpp.

References d.

Referenced by setReadChannelMode().

00791 {
00792     Q_D(QProcess);
00793     d->processChannelMode = mode;
00794 }

QProcess::ProcessChannel QProcess::readChannel (  )  const

Returns the current read channel of the QProcess.

See also:
setReadChannel()

Definition at line 801 of file qprocess.cpp.

References d.

Referenced by readAllStandardError(), and readAllStandardOutput().

00802 {
00803     Q_D(const QProcess);
00804     return d->processChannel;
00805 }

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

Changing the read channel will clear the unget buffer.

See also:
readChannel()

Definition at line 817 of file qprocess.cpp.

References d.

Referenced by readAllStandardError(), and readAllStandardOutput().

00818 {
00819     Q_D(QProcess);
00820     if (d->processChannel != channel)
00821         d->buffer.clear();
00822     d->processChannel = channel;
00823 }

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 835 of file qprocess.cpp.

References d, and StandardOutput.

00836 {
00837     Q_D(QProcess);
00838 
00839     if (channel == StandardOutput)
00840         d->stdoutChannel.closed = true;
00841     else
00842         d->stderrChannel.closed = true;
00843 }

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");
        more.closeWriteChannel();
        // QProcess will emit readyRead() once "more" starts printing

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

See also:
closeReadChannel()

Definition at line 869 of file qprocess.cpp.

References d.

Referenced by main().

00870 {
00871     Q_D(QProcess);
00872     d->stdinChannel.closed = true; // closing
00873     if (d->writeBuffer.isEmpty())
00874         d->closeWriteChannel();
00875 }

void QProcess::setStandardInputFile ( const QString fileName  ) 

Since:
4.2
Redirects the process' standard input to the file indicated by fileName. When an input redirection is in place, the QProcess object will be in read-only mode (calling write() will result in error).

If the file fileName does not exist at the moment start() is called or is not readable, starting the process will fail.

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

See also:
setStandardOutputFile(), setStandardErrorFile(), setStandardOutputProcess()

Definition at line 894 of file qprocess.cpp.

References d.

00895 {
00896     Q_D(QProcess);
00897     d->stdinChannel = fileName;
00898 }

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

Since:
4.2
Redirects the process' standard output to the file fileName. When the redirection is in place, the standard output read channel is closed: reading from it using read() will always fail, as will readAllStandardOutput().

If the file fileName 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 922 of file qprocess.cpp.

References QIODevice::Append, d, and QIODevice::Truncate.

00923 {
00924     Q_ASSERT(mode == Append || mode == Truncate);
00925     Q_D(QProcess);
00926 
00927     d->stdoutChannel = fileName;
00928     d->stdoutChannel.append = mode == Append;
00929 }

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

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

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 949 of file qprocess.cpp.

References QIODevice::Append, d, and QIODevice::Truncate.

00950 {
00951     Q_ASSERT(mode == Append || mode == Truncate);
00952     Q_D(QProcess);
00953 
00954     d->stderrChannel = fileName;
00955     d->stderrChannel.append = mode == Append;
00956 }

void QProcess::setStandardOutputProcess ( QProcess destination  ) 

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

The following shell command:

        command1 | command2

Can be accomplished with QProcesses with the following code:

        QProcess process1;
        QProcess process2;

        process1.setStandardOutputProcess(process2);

        process1.start("command1");
        process2.start("command2");

Definition at line 980 of file qprocess.cpp.

References QProcessPrivate::stdinChannel, and QProcessPrivate::stdoutChannel.

00981 {
00982     QProcessPrivate *dfrom = d_func();
00983     QProcessPrivate *dto = destination->d_func();
00984     dfrom->stdoutChannel.pipeTo(dto);
00985     dto->stdinChannel.pipeFrom(dfrom);
00986 }

QString QProcess::workingDirectory (  )  const

Returns the working directory that the QProcess will enter before the program has started.

See also:
setWorkingDirectory()

Definition at line 994 of file qprocess.cpp.

References d.

00995 {
00996     Q_D(const QProcess);
00997     return d->workingDirectory;
00998 }

void QProcess::setWorkingDirectory ( const QString dir  ) 

Sets the working directory to dir. QProcess will start the process in this directory. The default behavior is to start the process in the working directory of the calling process.

See also:
workingDirectory(), start()

Definition at line 1007 of file qprocess.cpp.

References d.

Referenced by Launcher::launchExample().

01008 {
01009     Q_D(QProcess);
01010     d->workingDirectory = dir;
01011 }

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:

snippets/qprocess-environment/main.cpp QProcess process; process.start

See also:
environment(), systemEnvironment()

Definition at line 1132 of file qprocess.cpp.

References d, and environment().

Referenced by Launcher::launchExample().

01133 {
01134     Q_D(QProcess);
01135     d->environment = environment;
01136 }

Here is the call graph for this function:

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(). If no environment has been set, the environment of the calling process will be used.

See also:
setEnvironment(), systemEnvironment()

Definition at line 1146 of file qprocess.cpp.

References d.

Referenced by setEnvironment().

01147 {
01148     Q_D(const QProcess);
01149     return d->environment;
01150 }

QProcess::ProcessError QProcess::error (  )  const

Returns the type of error that occurred last.

See also:
state()

Definition at line 1102 of file qprocess.cpp.

References d.

01103 {
01104     Q_D(const QProcess);
01105     return d->processError;
01106 }

QProcess::ProcessState QProcess::state (  )  const

Returns the current state of the process.

See also:
stateChanged(), error()

Definition at line 1113 of file qprocess.cpp.

References d.

Referenced by Launcher::launchExample(), QAssistantClient::openAssistant(), QAssistantClient::showPage(), and QAssistantClient::~QAssistantClient().

01114 {
01115     Q_D(const QProcess);
01116     return d->processState;
01117 }

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 1017 of file qprocess.cpp.

References d.

01018 {
01019     Q_D(const QProcess);
01020     return d->pid;
01021 }

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 1171 of file qprocess.cpp.

References d, emit, Running, started(), and Starting.

Referenced by QCleanlooksStylePrivate::lookupIconTheme(), main(), waitForBytesWritten(), and waitForFinished().

01172 {
01173     Q_D(QProcess);
01174     if (d->processState == QProcess::Starting) {
01175         if (!d->waitForStarted(msecs))
01176             return false;
01177         d->processState = QProcess::Running;
01178         emit started();
01179     }
01180     return d->processState == QProcess::Running;
01181 }

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

Reimplemented from QIODevice.

Definition at line 1185 of file qprocess.cpp.

References d, NotRunning, StandardError, and StandardOutput.

01186 {
01187     Q_D(QProcess);
01188 
01189     if (d->processState == QProcess::NotRunning)
01190         return false;
01191     if (d->processChannel == QProcess::StandardOutput && d->stdoutChannel.closed)
01192         return false;
01193     if (d->processChannel == QProcess::StandardError && d->stderrChannel.closed)
01194         return false;
01195     return d->waitForReadyRead(msecs);
01196 }

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

Reimplemented from QIODevice.

Definition at line 1200 of file qprocess.cpp.

References d, QTime::elapsed(), NotRunning, QTime::start(), started(), Starting, and waitForStarted().

Referenced by close().

01201 {
01202     Q_D(QProcess);
01203     if (d->processState == QProcess::NotRunning)
01204         return false;
01205     if (d->processState == QProcess::Starting) {
01206         QTime stopWatch;
01207         stopWatch.start();
01208         bool started = waitForStarted(msecs);
01209         if (!started)
01210             return false;
01211         if (msecs != -1)
01212             msecs -= stopWatch.elapsed();
01213     }
01214 
01215     return d->waitForBytesWritten(msecs);
01216 }

Here is the call graph for this function:

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 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:
finished(), waitForStarted(), waitForReadyRead(), waitForBytesWritten()

Definition at line 1236 of file qprocess.cpp.

References d, QTime::elapsed(), NotRunning, QTime::start(), started(), Starting, and waitForStarted().

Referenced by close(), QAssistantClient::closeAssistant(), Launcher::closeEvent(), qdesigner_internal::QDesignerResource::create(), execute(), QCleanlooksStylePrivate::lookupIconTheme(), main(), and ~QProcess().

01237 {
01238     Q_D(QProcess);
01239     if (d->processState == QProcess::NotRunning)
01240         return false;
01241     if (d->processState == QProcess::Starting) {
01242         QTime stopWatch;
01243         stopWatch.start();
01244         bool started = waitForStarted(msecs);
01245         if (!started)
01246             return false;
01247         if (msecs != -1)
01248             msecs -= stopWatch.elapsed();
01249     }
01250 
01251     return d->waitForFinished(msecs);
01252 }

Here is the call graph for this function:

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 1390 of file qprocess.cpp.

References data, QIODevice::readAll(), readChannel(), setReadChannel(), and StandardOutput.

Referenced by QAssistantClient::readPort().

01391 {
01392     ProcessChannel tmp = readChannel();
01393     setReadChannel(StandardOutput);
01394     QByteArray data = readAll();
01395     setReadChannel(tmp);
01396     return data;
01397 }

Here is the call graph for this function:

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 1406 of file qprocess.cpp.

References data, QIODevice::readAll(), readChannel(), setReadChannel(), and StandardError.

Referenced by main(), and QAssistantClient::readStdError().

01407 {
01408     ProcessChannel tmp = readChannel();
01409     setReadChannel(StandardError);
01410     QByteArray data = readAll();
01411     setReadChannel(tmp);
01412     return data;
01413 }

Here is the call graph for this function:

int QProcess::exitCode (  )  const

Returns the exit code of the last process that finished.

Definition at line 1590 of file qprocess.cpp.

References d.

Referenced by execute(), and main().

01591 {
01592     Q_D(const QProcess);
01593     return d->exitCode;
01594 }

QProcess::ExitStatus QProcess::exitStatus (  )  const

Since:
4.1
Returns the exit status of the last process that finished.

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 1605 of file qprocess.cpp.

References d.

Referenced by main().

01606 {
01607     Q_D(const QProcess);
01608     return d->exitStatus;
01609 }

qint64 QProcess::bytesAvailable (  )  const [virtual]

Reimplemented from QIODevice.

Definition at line 1076 of file qprocess.cpp.

References QIODevice::bytesAvailable(), d, qDebug(), QRingBuffer::size(), and StandardError.

01077 {
01078     Q_D(const QProcess);
01079     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
01080                                     ? &d->errorReadBuffer
01081                                     : &d->outputReadBuffer;
01082 #if defined QPROCESS_DEBUG
01083     qDebug("QProcess::bytesAvailable() == %i (%s)", readBuffer->size(),
01084            (d->processChannel == QProcess::StandardError) ? "stderr" : "stdout");
01085 #endif
01086     return readBuffer->size() + QIODevice::bytesAvailable();
01087 }

Here is the call graph for this function:

qint64 QProcess::bytesToWrite (  )  const [virtual]

Reimplemented from QIODevice.

Definition at line 1091 of file qprocess.cpp.

References d.

01092 {
01093     Q_D(const QProcess);
01094     return d->writeBuffer.size();
01095 }

bool QProcess::isSequential (  )  const [virtual]

Reimplemented from QIODevice.

Definition at line 1069 of file qprocess.cpp.

01070 {
01071     return true;
01072 }

bool QProcess::canReadLine (  )  const [virtual]

This function operates on the current read channel.

See also:
readChannel(), setReadChannel()

Reimplemented from QIODevice.

Definition at line 1029 of file qprocess.cpp.

References QIODevice::canReadLine(), QRingBuffer::canReadLine(), d, and StandardError.

01030 {
01031     Q_D(const QProcess);
01032     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
01033                                     ? &d->errorReadBuffer
01034                                     : &d->outputReadBuffer;
01035     return readBuffer->canReadLine() || QIODevice::canReadLine();
01036 }

Here is the call graph for this function:

void QProcess::close (  )  [virtual]

Closes all communication with the process. 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 1043 of file qprocess.cpp.

References QIODevice::aboutToClose(), emit, kill(), QIODevice::NotOpen, QIODevice::setOpenMode(), waitForBytesWritten(), and waitForFinished().

01044 {
01045     emit aboutToClose();
01046     while (waitForBytesWritten(-1))
01047         ;
01048     kill();
01049     waitForFinished(-1);
01050     setOpenMode(QIODevice::NotOpen);
01051 }

Here is the call graph for this function:

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 from QIODevice.

Definition at line 1058 of file qprocess.cpp.

References QIODevice::atEnd(), d, QRingBuffer::isEmpty(), QIODevice::isOpen(), and StandardError.

01059 {
01060     Q_D(const QProcess);
01061     const QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
01062                                     ? &d->errorReadBuffer
01063                                     : &d->outputReadBuffer;
01064     return QIODevice::atEnd() && (!isOpen() || readBuffer->isEmpty());
01065 }

Here is the call graph for this function:

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 by the calling process.

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

Definition at line 1622 of file qprocess.cpp.

References exitCode(), ForwardedChannels, setReadChannelMode(), start(), and waitForFinished().

01623 {
01624     QProcess process;
01625     process.setReadChannelMode(ForwardedChannels);
01626     process.start(program, arguments);
01627     process.waitForFinished(-1);
01628     return process.exitCode();
01629 }

Here is the call graph for this function:

int QProcess::execute ( const QString program  )  [static]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Starts the program program in a new process. 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 1638 of file qprocess.cpp.

References exitCode(), ForwardedChannels, setReadChannelMode(), start(), and waitForFinished().

01639 {
01640     QProcess process;
01641     process.setReadChannelMode(ForwardedChannels);
01642     process.start(program);
01643     process.waitForFinished(-1);
01644     return process.exitCode();
01645 }

Here is the call graph for this function:

bool QProcess::startDetached ( const QString program,
const QStringList arguments 
) [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.

On Unix, the started process will run in its own session and act like a daemon. On Windows, it will run as a regular standalone process.

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

Definition at line 1659 of file qprocess.cpp.

References QProcessPrivate::startDetached().

Referenced by launch().

01660 {
01661     return QProcessPrivate::startDetached(program, arguments);
01662 }

Here is the call graph for this function:

bool QProcess::startDetached ( const QString program  )  [static]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Starts the program program in a new process. 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 1674 of file qprocess.cpp.

References QList< T >::first(), parseCombinedArgString(), QList< T >::removeFirst(), and QProcessPrivate::startDetached().

01675 {
01676     QStringList args = parseCombinedArgString(program);
01677 
01678     QString prog = args.first();
01679     args.removeFirst();
01680 
01681     return QProcessPrivate::startDetached(prog, args);
01682 }

Here is the call graph for this function:

QStringList QProcess::systemEnvironment (  )  [static]

Since:
4.1
Returns the environment of the calling process as a list of key=value pairs. Example:

        QStringList environment = QProcess::systemEnvironment();
        // environment = {"PATH=/usr/bin:/usr/local/bin",
                          "USER=greg", "HOME=/home/greg"}

See also:
environment(), setEnvironment()

Definition at line 1705 of file qprocess.cpp.

References QString::fromLocal8Bit().

Referenced by PeerManager::PeerManager().

01706 {
01707     QStringList tmp;
01708     char *entry = 0;
01709     int count = 0;
01710     while ((entry = environ[count++]))
01711         tmp << QString::fromLocal8Bit(entry);
01712     return tmp;
01713 }

Here is the call graph for this function:

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 the process, and on Unix and Mac OS X the SIGTERM signal is sent.

See also:
kill()

Definition at line 1567 of file qprocess.cpp.

References d.

Referenced by QAssistantClient::closeAssistant(), Launcher::closeEvent(), and QAssistantClient::~QAssistantClient().

01568 {
01569     Q_D(QProcess);
01570     d->terminateProcess();
01571 }

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.

See also:
terminate()

Definition at line 1581 of file qprocess.cpp.

References d.

Referenced by close(), QAssistantClient::closeAssistant(), and ~QProcess().

01582 {
01583     Q_D(QProcess);
01584     d->killProcess();
01585 }

void QProcess::started (  )  [signal]

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

Referenced by waitForBytesWritten(), waitForFinished(), and waitForStarted().

void QProcess::finished ( int  exitCode  )  [signal]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Use finished(int exitCode, QProcess::ExitStatus status) instead.

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

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.

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.

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 {readChannel()}{read channel}.

See also:
readAllStandardOutput(), readChannel()

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 {readChannel()}{read channel}.

See also:
readAllStandardError(), readChannel()

void QProcess::setProcessState ( ProcessState  state  )  [protected]

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

See also:
state()

Definition at line 1259 of file qprocess.cpp.

References d.

01260 {
01261     Q_D(QProcess);
01262     d->processState = state;
01263 }

void QProcess::setupChildProcess (  )  [protected, virtual]

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 setupChildProcess();
            ...
        };

        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
        }

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

Definition at line 1299 of file qprocess.cpp.

01300 {
01301 }

qint64 QProcess::readData ( char *  data,
qint64  maxlen 
) [protected, virtual]

Implements QIODevice.

Definition at line 1305 of file qprocess.cpp.

References constData(), d, QRingBuffer::free(), QRingBuffer::getChar(), int, QRingBuffer::nextDataBlockSize(), ptr, qDebug(), qMin(), QRingBuffer::readPointer(), QRingBuffer::size(), and StandardError.

01306 {
01307     Q_D(QProcess);
01308     QRingBuffer *readBuffer = (d->processChannel == QProcess::StandardError)
01309                               ? &d->errorReadBuffer
01310                               : &d->outputReadBuffer;
01311 
01312     if (maxlen == 1) {
01313         int c = readBuffer->getChar();
01314         if (c == -1) {
01315 #if defined QPROCESS_DEBUG
01316             qDebug("QProcess::readData(%p \"%s\", %d) == -1",
01317                    data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
01318 #endif
01319             return -1;
01320         }
01321         *data = (char) c;
01322 #if defined QPROCESS_DEBUG
01323         qDebug("QProcess::readData(%p \"%s\", %d) == 1",
01324                data, qt_prettyDebug(data, 1, maxlen).constData(), 1);
01325 #endif
01326         return 1;
01327     }
01328 
01329     qint64 bytesToRead = qint64(qMin(readBuffer->size(), (int)maxlen));
01330     qint64 readSoFar = 0;
01331     while (readSoFar < bytesToRead) {
01332         const char *ptr = readBuffer->readPointer();
01333         int bytesToReadFromThisBlock = qMin<qint64>(bytesToRead - readSoFar,
01334                                             readBuffer->nextDataBlockSize());
01335         memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
01336         readSoFar += bytesToReadFromThisBlock;
01337         readBuffer->free(bytesToReadFromThisBlock);
01338     }
01339 
01340 #if defined QPROCESS_DEBUG
01341     qDebug("QProcess::readData(%p \"%s\", %lld) == %lld",
01342            data, qt_prettyDebug(data, readSoFar, 16).constData(), maxlen, readSoFar);
01343 #endif
01344     return readSoFar;
01345 }

Here is the call graph for this function:

qint64 QProcess::writeData ( const char *  data,
qint64  len 
) [protected, virtual]

Implements QIODevice.

Definition at line 1349 of file qprocess.cpp.

References constData(), d, and qDebug().

01350 {
01351     Q_D(QProcess);
01352 
01353     if (d->stdinChannel.closed) {
01354 #if defined QPROCESS_DEBUG
01355     qDebug("QProcess::writeData(%p \"%s\", %lld) == 0 (write channel closing)",
01356            data, qt_prettyDebug(data, len, 16).constData(), len);
01357 #endif
01358         return 0;
01359     }
01360 
01361     if (len == 1) {
01362         d->writeBuffer.putChar(*data);
01363         if (d->stdinChannel.notifier)
01364             d->stdinChannel.notifier->setEnabled(true);
01365 #if defined QPROCESS_DEBUG
01366     qDebug("QProcess::writeData(%p \"%s\", %lld) == 1 (written to buffer)",
01367            data, qt_prettyDebug(data, len, 16).constData(), len);
01368 #endif
01369         return 1;
01370     }
01371 
01372     char *dest = d->writeBuffer.reserve(len);
01373     memcpy(dest, data, len);
01374     if (d->stdinChannel.notifier)
01375         d->stdinChannel.notifier->setEnabled(true);
01376 #if defined QPROCESS_DEBUG
01377     qDebug("QProcess::writeData(%p \"%s\", %lld) == %lld (written to buffer)",
01378            data, qt_prettyDebug(data, len, 16).constData(), len, len);
01379 #endif
01380     return len;
01381 }

Here is the call graph for this function:

QProcess::Q_PRIVATE_SLOT ( d_func()  ,
bool   _q_canReadStandardOutput() 
) [private]

bool QProcess::_q_canReadStandardError (  )  [private]

bool bool QProcess::_q_canWrite (  )  [private]

bool bool bool QProcess::_q_startupNotification (  )  [private]

bool bool bool bool QProcess::_q_processDied (  )  [private]

bool bool bool bool void QProcess::_q_notified (  )  [private]


Friends And Related Function Documentation

Q_PID [related]

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

See also:
QProcess::pid()


The documentation for this class was generated from the following files:
Generated on Thu Mar 15 18:44:02 2007 for Qt 4.2 User's Guide by  doxygen 1.5.1