QProcess 类

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

Header: #include <QProcess>
qmake: QT += core
继承: QIODevice

注意: 此类的所有函数 可重入 .

公共类型

class CreateProcessArguments
typedef CreateProcessArgumentModifier
enum ExitStatus { NormalExit, CrashExit }
enum InputChannelMode { ManagedInputChannel, ForwardedInputChannel }
enum ProcessChannel { StandardOutput, StandardError }
enum ProcessChannelMode { SeparateChannels, MergedChannels, ForwardedChannels, ForwardedErrorChannel, ForwardedOutputChannel }
enum ProcessError { FailedToStart, Crashed, Timedout, WriteError, ReadError, UnknownError }
enum ProcessState { NotRunning, Starting, Running }

公共函数

QProcess (QObject * parent = Q_NULLPTR)
virtual ~QProcess ()
QStringList arguments () const
void closeReadChannel (ProcessChannel channel )
void closeWriteChannel ()
CreateProcessArgumentModifier createProcessArgumentsModifier () const
QProcess::ProcessError error () const
int exitCode () const
QProcess::ExitStatus exitStatus () const
InputChannelMode inputChannelMode () const
QString nativeArguments () const
ProcessChannelMode processChannelMode () const
QProcessEnvironment processEnvironment () const
qint64 processId () const
QString program () const
QByteArray readAllStandardError ()
QByteArray readAllStandardOutput ()
ProcessChannel readChannel () const
void setArguments (const QStringList & arguments )
void setCreateProcessArgumentsModifier (CreateProcessArgumentModifier modifier )
void setInputChannelMode (InputChannelMode mode )
void setNativeArguments (const QString & arguments )
void setProcessChannelMode (ProcessChannelMode mode )
void setProcessEnvironment (const QProcessEnvironment & environment )
void setProgram (const QString & program )
void setReadChannel (ProcessChannel channel )
void setStandardErrorFile (const QString & fileName , OpenMode mode = Truncate)
void setStandardInputFile (const QString & fileName )
void setStandardOutputFile (const QString & fileName , OpenMode mode = Truncate)
void setStandardOutputProcess (QProcess * destination )
void setWorkingDirectory (const QString & dir )
void start (const QString & program , const QStringList & arguments , OpenMode mode = ReadWrite)
void start (const QString & command , OpenMode mode = ReadWrite)
void start (OpenMode mode = ReadWrite)
QProcess::ProcessState state () const
bool waitForFinished (int msecs = 30000)
bool waitForStarted (int msecs = 30000)
QString workingDirectory () const

重实现公共函数

virtual bool atEnd () const
virtual qint64 bytesAvailable () const
virtual qint64 bytesToWrite () const
virtual bool canReadLine () const
virtual void close ()
virtual bool isSequential () const
virtual bool open (OpenMode mode = ReadWrite)
virtual bool waitForBytesWritten (int msecs = 30000)
virtual bool waitForReadyRead (int msecs = 30000)

公共槽

void kill ()
void terminate ()

信号

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

静态公共成员

int execute (const QString & program , const QStringList & arguments )
int execute (const QString & command )
QString nullDevice ()
bool startDetached (const QString & program , const QStringList & arguments , const QString & workingDirectory = QString(), qint64 * pid = Q_NULLPTR)
bool startDetached (const QString & command )
QStringList systemEnvironment ()

保护函数

void setProcessState (ProcessState state )
virtual void setupChildProcess ()

重实现保护函数

virtual qint64 readData (char * data , qint64 maxlen )
virtual qint64 writeData (const char * data , qint64 len )
typedef Q_PID

额外继承成员

详细描述

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

运行进程

要启动进程,把希望运行的程序名称和命令行自变量作为自变量传递给 start ()。自变量作为单字符串被提供采用 QStringList .

另外,可以设置要运行的程序采用 setProgram () 和 setArguments (),然后调用 start () 或 open ().

例如,以下代码片段通过在自变量列表中传递包含 -style 和 fusion 的字符串在 X11 平台运行 Fusion 风格的指针式时钟范例:

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

QProcess then enters the Starting state, and when the program has started, QProcess enters the 运行 状态并发射 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 。然后可以写入进程标准输入通过调用 write (),和读取标准输出通过调用 read (), readLine (),和 getChar ()。因为它继承 QIODevice , QProcess can also be used as an input source for QXmlReader , or for generating data to be uploaded using QNetworkAccessManager .

When the process exits, QProcess reenters the NotRunning 状态 (初始状态),并发射 finished ().

finished () 信号以自变量形式提供进程退出代码和退出状态,也可以调用 exitCode () 以获得最后完成进程的退出代码,和 exitStatus () to obtain its exit status. If an error occurs at any point in time, QProcess 将发射 errorOccurred () 信号。也可以调用 error () 以查找最后发生的错误类型,和 state () 以查找当前进程状态。

注意: QProcess is not supported on VxWorks 、iOS、tvOS、watchOS 或 UWP (通用 Windows 平台)。

凭借通道通信

进程有 2 个预定义输出通道:标准输出通道 ( stdout ) 提供常规控制台输出,和标准错误通道 ( stderr ) 通常提供由进程打印的错误。这些通道表示 2 个单独数据流。可以在它们之间切换通过调用 setReadChannel (). QProcess 发射 readyRead () 当当前读取通道数据可用时。它还发射 readyReadStandardOutput () 当新标准输出数据可用时,和当新标准错误数据可用时, readyReadStandardError () 被发射。代替调用 read (), readLine (),或 getChar (),可以明确读取 2 通道之一的所有数据通过调用 readAllStandardOutput () 或 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 () 采用 MergedChannels before starting the process to activate this feature. You also have the option of forwarding the output of the running process to the calling, main process, by passing ForwardedChannels as the argument. It is also possible to forward only one of the output channels - typically one would use ForwardedErrorChannel ,但 ForwardedOutputChannel also exists. Note that using channel forwarding is typically a bad idea in GUI applications - you should present errors graphically instead.

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

The positioning and the screen Z-order of windows belonging to GUI applications started with QProcess are controlled by the underlying windowing system. For Qt 5 applications, the positioning can be specified using the -qwindowgeometry command line option; X11 applications generally accept a -geometry command line option.

注意: On QNX, setting the working directory may cause all application threads, with the exception of the QProcess caller thread, to temporarily freeze during the spawning process, owing to a limitation in the operating system.

同步进程 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.

以下范例运行 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();
							

Windows 用户注意事项

某些 Windows 命令 (例如, 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.

另请参阅 QBuffer , QFile ,和 QTcpSocket .

成员类型文档编制

typedef QProcess:: CreateProcessArgumentModifier

注意: 此 typedef 只可用于桌面 Windows。

在 Windows, QProcess 使用 Win32 API 函数 CreateProcess 去启动子级进程。而 QProcess 提供启动进程的舒适方式而无需担心平台细节,在某些情况下调优是可取的将参数传递给 CreateProcess 。这被履行通过定义 CreateProcessArgumentModifier 函数并把它传递给 setCreateProcessArgumentsModifier .

CreateProcessArgumentModifier 函数接受一参数:指针指向 CreateProcessArguments 结构。此结构的成员会被传递给 CreateProcess 后于 CreateProcessArgumentModifier 函数被调用。

以下范例演示如何把自定义标志传递给 CreateProcess 。当从控制台进程 A 启动控制台进程 B 时, QProcess 默认情况下,进程 B 将重用进程 A 的控制台窗口。在此范例中,将为子级进程 B 创建具有自定义配色方案的新控制台窗口。

    QProcess process;
    process.setCreateProcessArgumentsModifier([] (QProcess::CreateProcessArguments *args)
    {
        args->flags |= CREATE_NEW_CONSOLE;
        args->startupInfo->dwFlags &= ~STARTF_USESTDHANDLES;
        args->startupInfo->dwFlags |= STARTF_USEFILLATTRIBUTE;
        args->startupInfo->dwFillAttribute = BACKGROUND_BLUE | FOREGROUND_RED
                                           | FOREGROUND_INTENSITY;
    });
    process.start("C:\\Windows\\System32\\cmd.exe", QStringList() << "/k" << "title" << "The Child Process");
							

另请参阅 QProcess::CreateProcessArguments and setCreateProcessArgumentsModifier ().

enum QProcess:: ExitStatus

此枚举描述不同退出状态为 QProcess .

常量 描述
QProcess::NormalExit 0 进程正常退出。
QProcess::CrashExit 1 进程崩溃。

另请参阅 exitStatus ().

enum QProcess:: InputChannelMode

此枚举描述进程输入通道模式为 QProcess 。将这些值之一传递给 setInputChannelMode () 去设置当前写入通道模式。

常量 描述
QProcess::ManagedInputChannel 0 QProcess 管理正运行进程的输入。这是默认输入通道模式为 QProcess .
QProcess::ForwardedInputChannel 1 QProcess 把主进程的输入转发给正运行进程。子级进程从与主进程相同的源读取其标准输入。注意:主进程不得试着读取其标准输入当子级进程正在运行时。

该枚举在 Qt 5.2 引入或被修改。

另请参阅 setInputChannelMode ().

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 正运行进程的 stdout (标准输出)。
QProcess::StandardError 1 正运行进程的 stderr (标准错误)。

另请参阅 setReadChannel ().

enum QProcess:: ProcessChannelMode

此枚举描述进程的输出通道模式为 QProcess 。将这些值之一传递给 setProcessChannelMode () 以设置当前读取通道模式。

常量 描述
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.
QProcess::ForwardedErrorChannel 4 QProcess manages the standard output of the running process, but forwards its standard error onto the main process. This reflects the typical use of command line tools as filters, where the standard output is redirected to another process or a file, while standard error is printed to the console for diagnostic purposes. (This value was introduced in Qt 5.2.)
QProcess::ForwardedOutputChannel 3 与 ForwardedErrorChannel 互补。(该值在 Qt 5.2 引入。)

注意: Windows intentionally suppresses output from GUI-only applications to inherited consoles. This does not apply to output redirected to files or pipes. To forward the output of GUI-only applications on the console nonetheless, you must use SeparateChannels and do the forwarding yourself by reading the output and writing it to the appropriate output channels.

另请参阅 setProcessChannelMode ().

enum QProcess:: ProcessError

此枚举描述错误的不同类型,报告通过 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 发生未知错误。这是默认返回值为 error ().

另请参阅 error ().

enum QProcess:: ProcessState

此枚举描述不同状态为 QProcess .

常量 描述
QProcess::NotRunning 0 进程未运行。
QProcess::Starting 1 进程正在启动,但尚未援引程序。
QProcess::Running 2 进程正在运行且读写就绪。

另请参阅 state ().

成员函数文档编制

QProcess:: QProcess ( QObject * parent = Q_NULLPTR)

构造 QProcess 对象采用给定 parent .

[virtual] QProcess:: ~QProcess ()

销毁 QProcess 对象,即:杀除进程。

注意:此函数不会返回直到进程被终止。

QStringList QProcess:: arguments () const

返回上次启动进程采用的命令行自变量。

该函数在 Qt 5.0 引入。

另请参阅 setArguments () 和 start ().

[virtual] bool QProcess:: atEnd () const

重实现自 QIODevice::atEnd ().

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

[virtual] qint64 QProcess:: bytesAvailable () const

重实现自 QIODevice::bytesAvailable ().

[virtual] qint64 QProcess:: bytesToWrite () const

重实现自 QIODevice::bytesToWrite ().

[virtual] bool QProcess:: canReadLine () const

重实现自 QIODevice::canReadLine ().

此函数运转于当前读取通道。

另请参阅 readChannel () 和 setReadChannel ().

[virtual] void QProcess:: close ()

重实现自 QIODevice::close ().

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.

void QProcess:: closeReadChannel ( ProcessChannel channel )

关闭读取通道 channel 。在调用此函数后, 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.

另请参阅 closeWriteChannel () 和 setReadChannel ().

void QProcess:: closeWriteChannel ()

Schedules the write channel of QProcess to be closed. The channel will close once all data has been written to the process. After calling this 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 () 被调用。

另请参阅 closeReadChannel ().

CreateProcessArgumentModifier QProcess:: createProcessArgumentsModifier () const

返回先前设置的 CreateProcess 修饰符函数。

注意: 此函数只可用于 Windows 平台。

该函数在 Qt 5.7 引入。

另请参阅 setCreateProcessArgumentsModifier () 和 QProcess::CreateProcessArgumentModifier .

QProcess::ProcessError QProcess:: error () const

返回最后发生的错误类型。

另请参阅 state ().

[signal] void QProcess:: errorOccurred ( QProcess::ProcessError error )

此信号被发射当进程发生错误时。指定 error 描述发生的错误类型。

该函数在 Qt 5.6 引入。

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

启动程序 program 采用自变量 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.

Argument handling is identical to the respective start () overload.

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

另请参阅 start ().

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

这是重载函数。

启动程序 command in a new process, waits for it to finish, and then returns the exit code.

Argument handling is identical to the respective start () overload.

After the command string has been split and unquoted, this function behaves like the overload which takes the arguments as a string list.

另请参阅 start ().

int QProcess:: exitCode () const

返回最后完成进程的退出代码。

此值无效除非 exitStatus () 返回 NormalExit .

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 引入。

[signal] void QProcess:: finished ( int exitCode , QProcess::ExitStatus exitStatus )

This signal is emitted when the process finishes. exitCode is the exit code of the process (only valid for normal exits), and exitStatus is the exit status. After the process has finished, the buffers in QProcess are still intact. You can still read any data that the process may have written before it finished.

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

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

另请参阅 exitStatus ().

InputChannelMode QProcess:: inputChannelMode () const

Returns the channel mode of the QProcess standard input channel.

该函数在 Qt 5.2 引入。

另请参阅 setInputChannelMode () 和 InputChannelMode .

[virtual] bool QProcess:: isSequential () const

重实现自 QIODevice::isSequential ().

[slot] void QProcess:: kill ()

杀除当前进程,导致它立即退出。

在 Windows,kill() 使用 TerminateProcess,而在 Unix 和 macOS,把 SIGKILL 信号发送给进程。

另请参阅 terminate ().

QString QProcess:: nativeArguments () const

Returns the additional native command line arguments for the program.

注意: 此函数只可用于 Windows 平台。

该函数在 Qt 4.7 引入。

另请参阅 setNativeArguments ().

[static] QString QProcess:: nullDevice ()

操作系统的 null 设备。

返回的文件路径使用本机目录分隔符。

该函数在 Qt 5.2 引入。

另请参阅 QProcess::setStandardInputFile (), QProcess::setStandardOutputFile (),和 QProcess::setStandardErrorFile ().

[virtual] bool QProcess:: open ( OpenMode mode = ReadWrite)

重实现自 QIODevice::open ().

Starts the program set by setProgram () with arguments set by setArguments ()。 OpenMode is set to mode .

This method is an alias for start (), and exists only to fully implement the interface defined by QIODevice .

另请参阅 start (), setProgram (),和 setArguments ().

ProcessChannelMode QProcess:: processChannelMode () const

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

该函数在 Qt 4.2 引入。

另请参阅 setProcessChannelMode (), ProcessChannelMode ,和 setReadChannel ().

QProcessEnvironment QProcess:: processEnvironment () const

Returns the environment that QProcess will pass to its child process, or an empty object if no environment has been set using setEnvironment() or setProcessEnvironment (). If no environment has been set, the environment of the calling process will be used.

该函数在 Qt 4.6 引入。

另请参阅 setProcessEnvironment (), setEnvironment (),和 QProcessEnvironment::isEmpty ().

qint64 QProcess:: processId () const

返回正在运行进程的本机进程标识符,若可用。若目前没有进程正在运行, 0 被返回。

该函数在 Qt 5.3 引入。

QString QProcess:: program () const

返回进程最后一次启动时采用的程序。

该函数在 Qt 5.0 引入。

另请参阅 setProgram () 和 start ().

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 .

另请参阅 readyReadStandardError (), readAllStandardOutput (), readChannel (),和 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 .

另请参阅 readyReadStandardOutput (), readAllStandardError (), readChannel (),和 setReadChannel ().

ProcessChannel QProcess:: readChannel () const

返回当前读取通道为 QProcess .

另请参阅 setReadChannel ().

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

重实现自 QIODevice::readData ().

[signal] void QProcess:: readyReadStandardError ()

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 .

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

另请参阅 readAllStandardError () 和 readChannel ().

[signal] void QProcess:: readyReadStandardOutput ()

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 .

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

另请参阅 readAllStandardOutput () 和 readChannel ().

void QProcess:: setArguments (const QStringList & arguments )

设置 arguments to pass to the called program when starting the process. This function must be called before start ().

该函数在 Qt 5.1 引入。

另请参阅 start (), setProgram (),和 arguments ().

void QProcess:: setCreateProcessArgumentsModifier ( CreateProcessArgumentModifier modifier )

设置 modifier CreateProcess Win32 API 调用。传递 QProcess::CreateProcessArgumentModifier() 以移除先前设置的。

注意: 此函数只可用于 Windows 平台且要求 C++ 11。

该函数在 Qt 5.7 引入。

另请参阅 createProcessArgumentsModifier () 和 QProcess::CreateProcessArgumentModifier .

void QProcess:: setInputChannelMode ( InputChannelMode mode )

Sets the channel mode of the QProcess standard input channel to the mode specified. This mode will be used the next time start () 被调用。

该函数在 Qt 5.2 引入。

另请参阅 inputChannelMode () 和 InputChannelMode .

void QProcess:: setNativeArguments (const QString & arguments )

这是重载函数。

Sets additional native command line arguments for the program.

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.

注意: 此函数只可用于 Windows 平台。

该函数在 Qt 4.7 引入。

另请参阅 nativeArguments ().

void QProcess:: setProcessChannelMode ( ProcessChannelMode mode )

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

QProcess builder;
builder.setProcessChannelMode(QProcess::MergedChannels);
builder.start("make", QStringList() << "-j2");
if (!builder.waitForFinished())
    qDebug() << "Make failed:" << builder.errorString();
else
    qDebug() << "Make output:" << builder.readAll();
							

该函数在 Qt 4.2 引入。

另请参阅 processChannelMode (), ProcessChannelMode ,和 setReadChannel ().

void QProcess:: setProcessEnvironment (const QProcessEnvironment & environment )

设置 environment that QProcess 将传递给子级进程。

例如,以下代码添加环境变量 TMPDIR :

QProcess process;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("TMPDIR", "C:\\MyApp\\temp"); // Add an environment variable
process.setProcessEnvironment(env);
process.start("myapp");
							

注意:在 Windows,环境变量名称是不区分大小写的。

该函数在 Qt 4.6 引入。

另请参阅 processEnvironment (), QProcessEnvironment::systemEnvironment (),和 setEnvironment ().

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

设置当前状态为 QProcess state 指定。

另请参阅 state ().

void QProcess:: setProgram (const QString & program )

设置 program to use when starting the process. This function must be called before start ().

该函数在 Qt 5.1 引入。

另请参阅 start (), setArguments (),和 program ().

void QProcess:: setReadChannel ( ProcessChannel channel )

设置当前读取通道为 QProcess 到给定 channel . The current input channel is used by the functions read (), readAll (), readLine (),和 getChar (). It also determines which channel triggers QProcess to emit readyRead ().

另请参阅 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.

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

Note: if setProcessChannelMode () was called with an argument of QProcess::MergedChannels ,此函数不起作用。

该函数在 Qt 4.2 引入。

另请参阅 setStandardInputFile (), setStandardOutputFile (),和 setStandardOutputProcess ().

void QProcess:: setStandardInputFile (const QString & fileName )

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

To make the process read EOF right away, pass nullDevice () here. This is cleaner than using closeWriteChannel () before writing any data, because it can be set up prior to starting the process.

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 引入。

另请参阅 setStandardOutputFile (), setStandardErrorFile (),和 setStandardOutputProcess ().

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

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

To discard all standard output from the process, pass nullDevice () here. This is more efficient than simply never reading the standard output, as no QProcess buffers are filled.

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 引入。

另请参阅 setStandardInputFile (), setStandardErrorFile (),和 setStandardOutputProcess ().

void QProcess:: setStandardOutputProcess ( QProcess * destination )

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

以下 Shell 命令:

command1 | command2
							

Can be accomplished with QProcess 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 )

把工作目录设为 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.

注意: On QNX, this may cause all application threads to temporarily freeze.

另请参阅 workingDirectory () 和 start ().

[virtual protected] void QProcess:: setupChildProcess ()

This function is called in the child process context just before the program is executed on Unix or macOS (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
}
							

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

警告: 此函数被调用由 QProcess on Unix and macOS only. On Windows and QNX, it is not called.

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

启动给定 program 在新进程,传递的命令行自变量在 arguments .

QProcess object will immediately enter the Starting state. If the process starts successfully, QProcess will emit started (); otherwise, errorOccurred () will be emitted.

注意: Processes are started asynchronously, which means the started () 和 errorOccurred () signals may be delayed. Call waitForStarted () to make sure the process has started (or has failed to start) and those signals have been emitted.

注意: 不履行进一步的自变量分割。

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

OpenMode is set to mode .

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

另请参阅 processId (), started (), waitForStarted (),和 setNativeArguments ().

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

这是重载函数。

Starts the command command in a new process. The OpenMode is set to mode .

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

Arguments containing spaces must be quoted to be correctly supplied to the new process. For example:

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

Literal quotes in the command string are represented by triple quotes. For example:

QProcess process;
process.start("dir \"Epic 12\"\"\" Singles\"");
							

After the command string has been split and unquoted, this function behaves like the overload which takes the arguments as a string list.

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

On operating systems where the system API for passing command line arguments to a subprocess natively uses a single string (Windows), one can conceive command lines which cannot be passed via QProcess 's portable list-based API. In these rare cases you need to use setProgram () 和 setNativeArguments () instead of this function.

void QProcess:: start ( OpenMode mode = ReadWrite)

这是重载函数。

Starts the program set by setProgram () with arguments set by setArguments ()。 OpenMode is set to mode .

该函数在 Qt 5.1 引入。

另请参阅 open (), setProgram (),和 setArguments ().

[static] bool QProcess:: startDetached (const QString & program , const QStringList & arguments , const QString & workingDirectory = QString(), qint64 * pid = Q_NULLPTR)

启动程序 program 采用自变量 arguments in a new process, and detaches from it. Returns true 当成功时;否则返回 false . If the calling process exits, the detached process will continue to run unaffected.

Argument handling is identical to the respective start () overload.

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

The process will be started in the directory workingDirectory 。若 workingDirectory is empty, the working directory is inherited from the calling process.

注意: 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.

另请参阅 start ().

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

这是重载函数。

Starts the command command in a new process, and detaches from it. Returns true 当成功时;否则返回 false .

Argument handling is identical to the respective start () overload.

After the command string has been split and unquoted, this function behaves like the overload which takes the arguments as a string list.

另请参阅 start (const QString &command, OpenMode mode).

[signal] void QProcess:: started ()

此信号被发射由 QProcess 当此过程已开始,且 state () 返回 运行 .

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

QProcess::ProcessState QProcess:: state () const

返回进程的当前状态。

另请参阅 stateChanged () 和 error ().

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

此信号被发射每当状态为 QProcess 改变。 newState 自变量为状态 QProcess 要改变。

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

[static] QStringList QProcess:: systemEnvironment ()

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"}
							

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

注意: For new code, it is recommended to use QProcessEnvironment::systemEnvironment ()

该函数在 Qt 4.1 引入。

另请参阅 QProcessEnvironment::systemEnvironment () 和 setProcessEnvironment ().

[slot] void QProcess:: terminate ()

试图终止进程。

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 top-level windows of the process and then to the main thread of the process itself. On Unix and macOS 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 ().

另请参阅 kill ().

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

重实现自 QIODevice::waitForBytesWritten ().

bool QProcess:: waitForFinished ( int msecs = 30000)

Blocks until the process has finished and the finished () 信号已发射,或直到 msecs 毫秒已过去。

返回 true if the process finished; otherwise returns false (若操作超时,若发生错误,或者若此 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.

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

若 msecs 为 -1,此函数不会超时。

另请参阅 finished (), waitForStarted (), waitForReadyRead (),和 waitForBytesWritten ().

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

重实现自 QIODevice::waitForReadyRead ().

bool QProcess:: waitForStarted ( int msecs = 30000)

阻塞直到进程启动且 started () 信号已发射,或直到 msecs 毫秒已过去。

返回 true 若进程成功启动;否则返回 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.

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

若 msecs 为 -1,此函数不会超时。

注意: 在某些 UNIX 操作系统,此函数可能返回 true 但进程可能稍后报告 QProcess::FailedToStart 错误。

另请参阅 started (), waitForReadyRead (), waitForBytesWritten (),和 waitForFinished ().

QString QProcess:: workingDirectory () const

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.

另请参阅 setWorkingDirectory ().

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

重实现自 QIODevice::writeData ().

相关非成员

typedef Q_PID

Typedef for the identifiers used to represent processes on the underlying platform. On Unix, this corresponds to qint64 ;在 Windows,它相当于 _PROCESS_INFORMATION* .

另请参阅 QProcess::pid ().

宏文档编制

QT_NO_PROCESS_COMBINED_ARGUMENT_START

禁用 QProcess::start() overload taking a single string. In most cases where it is used, the user intends for the first argument to be treated atomically as per the other overload.

该函数在 Qt 5.6 引入。

另请参阅 QProcess::start (const QString &command, OpenMode mode).