Qt:Документация 4.3.2/qprocess

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
40px Внимание: Актуальная версия перевода документации находится здесь

__NOTOC__

Image:qt-logo.png

Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Image:trolltech-logo.png

Содержание

QProcess Class Reference
[модуль QtCore ]

The QProcess class is used to start external programs and to communicate with them. Далее...

 #include <QProcess>

Наследует QIODevice.

Примечание: все функции в этом классе реентерабельны.

Открытые типы

Открытые функции

  • 32 открытые функции, унаследованные от QIODevice
  • 29 открытых функций, унаследованных от QObject

Открытые слоты

  • 1 открытый слот, унаследованный от QObject

Сигналы

  • 3 сигнала, унаследованные от QIODevice
  • 1 сигнал, унаследованный от QObject

Статические открытые члены

  • int execute ( const QString & program, const QStringList & arguments )
  • int execute ( const QString & program )
  • bool startDetached ( const QString & program, const QStringList & arguments, const QString & workingDirectory, qint64 * pid = 0 )
  • bool startDetached ( const QString & program, const QStringList & arguments )
  • bool startDetached ( const QString & program )
  • QStringList systemEnvironment ()
  • 5 статических открытых членов, унаследованных от QObject

Защищенные функции

  • 5 защищенных функций, унаследованных от QIODevice
  • 7 защищенных функций, унаследованных от QObject

Связанные не-члены

Дополнительные унаследованные члены

  • 1 свойство, унаследованное от QObject

Подробное описание

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(). Пример:

     QObject *parent;
     ...
     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.

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:

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!");
     gzip.closeWriteChannel();
 
     if (!gzip.waitForFinished())
         return false;
 
     QByteArray result = gzip.readAll();

See also QBuffer, QFile, and QTcpSocket.


Описание типов

enum QProcess::ExitStatus

This enum describes the different exit statuses of QProcess.


Константа Значение Описание
QProcess::NormalExit 0 The process exited normally.
QProcess::CrashExit 1 The process crashed.

See also exitStatus().

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.


Константа Значение Описание
QProcess::StandardOutput 0 The standard output (stdout) of the running process.
QProcess::StandardError 1 The standard error (stderr) of the running process.

See also setReadChannel().

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.


Константа Значение Описание
QProcess::SeparateChannels 0 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.
QProcess::MergedChannels 1 QProcess merges the output of the running process into the standard output channel (stdout). The standard error channel (stderr) will not receive any data. The standard output and standard error data of the running process are interleaved.
QProcess::ForwardedChannels 2 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().

enum QProcess::ProcessError

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


Константа Значение Описание
QProcess::FailedToStart 0 The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.
QProcess::Crashed 1 The process crashed some time after starting successfully.
QProcess::Timedout 2 The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.
QProcess::WriteError 4 An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel.
QProcess::ReadError 3 An error occurred when attempting to read from the process. For example, the process may not be running.
QProcess::UnknownError 5 An unknown error occurred. This is the default return value of error().

Смотрие также error().

enum QProcess::ProcessState

This enum describes the different states of QProcess.


Константа Значение Описание
QProcess::NotRunning 0 The process is not running.
QProcess::Starting 1 The process is starting, but the program has not yet been invoked.
QProcess::Running 2 The process is running and is ready for reading and writing.

Смотрите также state().


Описание функций-членов

QProcess::QProcess ( QObject * parent = 0 )

Constructs a QProcess object with the given parent.

QProcess::~QProcess () [virtual]

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

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

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.

Переопределено из QIODevice.

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

void QProcess::closeWriteChannel ()

Schedules the write channel of QProcess to be closed. The channel will close once all data has been written to the process. After calling this 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. Пример:

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

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

QProcess::ProcessError QProcess::error () const

Returns the type of error that occurred last.

Смотрите также state().

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.

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.

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

Эта перегруженная функция предоставлена для удобства.

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.

int QProcess::exitCode () const

Returns the exit code of the last process that finished.

QProcess::ExitStatus QProcess::exitStatus () const

Returns the exit status of the last process that finished.

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

Эта функция была введена в Qt 4.1.

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

Q_PID QProcess::pid () const

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

ProcessChannelMode QProcess::processChannelMode () const

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

Эта функция была введена в Qt 4.2.

See also setProcessChannelMode(), setReadChannelMode(), ProcessChannelMode, and setReadChannel().

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(), and setReadChannel().

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(), and setReadChannel().

ProcessChannel QProcess::readChannel () const

Returns the current read channel of the QProcess.

See also setReadChannel().

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

void QProcess::readyReadStandardOutput () [signal]

This signal is emitted when the process has made new data available through its standard output channel (stdout). It is emitted regardless of the current read channel.

See also readAllStandardOutput() and readChannel().

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;
 QStringList env = QProcess::systemEnvironment();
 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");

See also environment() and systemEnvironment().

void QProcess::setProcessChannelMode ( ProcessChannelMode mode )

Sets the channel mode of the QProcess standard output and standard error channels to the mode specified. This mode will be used the next time start() is called. Пример:

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

Эта функция была введена в Qt 4.2.

See also processChannelMode(), readChannelMode(), ProcessChannelMode, and setReadChannel().

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

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

Смотрите также state().

void QProcess::setReadChannel ( ProcessChannel channel )

Sets the current read channel of the QProcess to the given channel. The current input channel is used by the functions read(), readAll(), readLine(), and getChar(). It also determines which channel triggers QProcess to emit readyRead().

See also readChannel().

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

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

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.

Эта функция была введена в Qt 4.2.

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

void QProcess::setStandardInputFile ( const QString & fileName )

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

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

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

Эта функция была введена в Qt 4.2.

See also setStandardOutputFile(), setStandardErrorFile(), and setStandardOutputProcess().

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

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

If the file fileName 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.

Эта функция была введена в Qt 4.2.

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

void QProcess::setStandardOutputProcess ( QProcess * destination )

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

The following shell command:

 command1 | command2

Can be accomplished with QProcesses with the following code:

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

Эта функция была введена в Qt 4.2.

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

void QProcess::setupChildProcess () [virtual protected]

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. Пример:

 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.

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(), and waitForStarted().

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

Эта перегруженная функция предоставлена для удобства.

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. Пример:

 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. Пример:

 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.

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. Возвращает true, если всё прошло успешно; в противном случае возвращает 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.

The process will be started in the directory workingDirectory.

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

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. Возвращает true, если всё прошло успешно; в противном случае возвращает 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.

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

Эта перегруженная функция предоставлена для удобства.

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.

void QProcess::started () [signal]

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

QProcess::ProcessState QProcess::state () const

Returns the current state of the process.

See also stateChanged() and error().

void QProcess::stateChanged ( QProcess::ProcessState newState ) [signal]

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

QStringList QProcess::systemEnvironment () [static]

Returns the environment of the calling process as a list of key=value pairs. Пример:

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

Эта функция была введена в Qt 4.1.

See also environment() and setEnvironment().

void QProcess::terminate () [slot]

Attempts to terminate the process.

The process may not exit as a result of calling this function (it is given the chance to prompt the user for any unsaved files, etc).

On Windows, terminate() posts a WM_CLOSE message to all toplevel windows of the process and then to the main thread of the process itself. On Unix and Mac OS X the SIGTERM signal is sent.

Console applications on Windows that do not run an event loop, or whose event loop does not handle the WM_CLOSE message, can only be terminated by calling kill().

See also kill().

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.

Если задать время таймаута как -1, таймер будет отключён.

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

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.

Если задать время таймаута как -1, таймер будет отключён.

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

QString QProcess::workingDirectory () const

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

See also setWorkingDirectory().


Связанные не-члены

typedef Q_PID

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



Copyright © 2007 Trolltech Trademarks
Qt 4.3.2