QProcess 類用於啓動外部程序並與之通信。 更多...
| 頭: |
#include <QProcess>
|
| CMake: |
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
|
| qmake: |
QT += core
|
| 繼承: | QIODevice |
注意: 此類的所有函數 可重入 .
| struct | CreateProcessArguments |
(從 6.6 起)
struct
|
UnixProcessParameters |
| 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 } |
(從 6.6 起)
枚舉類
|
UnixProcessFlag { CloseFileDescriptors, CreateNewSession, DisconnectControllingTerminal, IgnoreSigPipe, ResetIds, …, DisableCoreDumps } |
| flags | UnixProcessFlags |
| QProcess (QObject * parent = nullptr) | |
| virtual | ~QProcess () |
| QStringList | arguments () const |
(從 6.0 起)
std::function<void ()>
|
childProcessModifier () const |
| void | closeReadChannel (QProcess::ProcessChannel channel ) |
| void | closeWriteChannel () |
| QProcess::CreateProcessArgumentModifier | createProcessArgumentsModifier () const |
| QProcess::ProcessError | error () const |
| int | exitCode () const |
| QProcess::ExitStatus | exitStatus () const |
(從 6.7 起)
void
|
failChildProcessModifier (const char * 描述 , int error = 0) |
| QProcess::InputChannelMode | inputChannelMode () const |
| QString | nativeArguments () const |
| QProcess::ProcessChannelMode | processChannelMode () const |
| QProcessEnvironment | processEnvironment () const |
| qint64 | processId () const |
| QString | program () const |
| QByteArray | readAllStandardError () |
| QByteArray | readAllStandardOutput () |
| QProcess::ProcessChannel | readChannel () const |
| void | setArguments (const QStringList & arguments ) |
(從 6.0 起)
void
|
setChildProcessModifier (const std::function<void ()> & modifier ) |
| void | setCreateProcessArgumentsModifier (QProcess::CreateProcessArgumentModifier modifier ) |
| void | setInputChannelMode (QProcess::InputChannelMode mode ) |
| void | setNativeArguments (const QString & arguments ) |
| void | setProcessChannelMode (QProcess::ProcessChannelMode mode ) |
| void | setProcessEnvironment (const QProcessEnvironment & environment ) |
| void | setProgram (const QString & program ) |
| void | setReadChannel (QProcess::ProcessChannel channel ) |
| void | setStandardErrorFile (const QString & fileName , QIODeviceBase::OpenMode mode = Truncate) |
| void | setStandardInputFile (const QString & fileName ) |
| void | setStandardOutputFile (const QString & fileName , QIODeviceBase::OpenMode mode = Truncate) |
| void | setStandardOutputProcess (QProcess * destination ) |
(從 6.6 起)
void
|
setUnixProcessParameters (const QProcess::UnixProcessParameters & params ) |
(從 6.6 起)
void
|
setUnixProcessParameters (QProcess::UnixProcessFlags flagsOnly ) |
| void | setWorkingDirectory (const QString & dir ) |
| void | start (const QString & program , const QStringList & arguments = {}, QIODeviceBase::OpenMode mode = ReadWrite) |
| void | start (QIODeviceBase::OpenMode mode = ReadWrite) |
(從 6.0 起)
void
|
startCommand (const QString & command , QIODeviceBase::OpenMode mode = ReadWrite) |
| bool | startDetached (qint64 * pid = nullptr) |
| QProcess::ProcessState | state () const |
(從 6.6 起)
QProcess::UnixProcessParameters
|
unixProcessParameters () const |
| bool | waitForFinished (int msecs = 30000) |
| bool | waitForStarted (int msecs = 30000) |
| QString | workingDirectory () const |
| virtual qint64 | bytesToWrite () const override |
| virtual void | close () override |
| virtual bool | isSequential () const override |
| virtual bool | open (QIODeviceBase::OpenMode mode = ReadWrite) override |
| virtual bool | waitForBytesWritten (int msecs = 30000) override |
| virtual bool | waitForReadyRead (int msecs = 30000) override |
| void | kill () |
| void | terminate () |
| void | errorOccurred (QProcess::ProcessError error ) |
| void | finished (int exitCode , QProcess::ExitStatus exitStatus = NormalExit) |
| void | readyReadStandardError () |
| void | readyReadStandardOutput () |
| void | started () |
| void | stateChanged (QProcess::ProcessState newState ) |
| int | execute (const QString & program , const QStringList & arguments = {}) |
| QString | nullDevice () |
| QStringList | splitCommand (QStringView command ) |
| bool | startDetached (const QString & program , const QStringList & arguments = {}, const QString & workingDirectory = QString(), qint64 * pid = nullptr) |
| QStringList | systemEnvironment () |
| void | setProcessState (QProcess::ProcessState state ) |
| virtual qint64 | readData (char * data , qint64 maxlen ) override |
要啓動進程,把希望運行的程序名稱和命令行自變量作為自變量傳遞給 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 然後進入 Starting 狀態,和當程序啓動時,QProcess 進入 運行 狀態並發射 started ().
QProcess 允許把進程視為順序 I/O 設備。可以讀寫進程,就像訪問網絡連接使用 QTcpSocket 。然後可以寫入進程標準輸入通過調用 write (),和讀取標準輸齣通過調用 read (), readLine (),和 getChar ()。因為它繼承 QIODevice ,QProcess 還可以用作輸入源對於 QXmlReader ,或對於生成要上傳的數據使用 QNetworkAccessManager .
當進程退齣時,QProcess 重新進入 NotRunning 狀態 (初始狀態),並發射 finished ().
The finished () 信號以自變量形式提供進程退齣代碼和退齣狀態,也可以調用 exitCode () 以獲得最後完成進程的退齣代碼,和 exitStatus () 以獲得其退齣狀態。若在任何時間點齣現錯誤,QProcess 將發射 errorOccurred () 信號。也可以調用 error () 以查找最後齣現的錯誤類型,和 state () 以查找當前進程狀態。
注意: QProcess 不支持 VxWorks iOS tvOS 或 watchOS。
可以設置要運行程序通過調用 setProgram () 或直接在 start () 調用。效果按調用 start () 采用程序名稱和自變量,相當於調用 setProgram () 和 setArguments () 在該函數之前,然後調用沒有那些參數的重載。
QProcess 以 3 種不同方式之一解釋程序名,類似於 Unix Shell 和 Windows 命令解釋器在它們自己的命令行中如何操作:
PATH
environment variable; on Windows, the search is performed by the OS and will first the parent process' current directory before the
PATH
environment variable (see the documentation for
CreateProcess
for the full list).
To avoid platform-dependent behavior or any issues with how the current application was launched, it is advisable to always pass an absolute path to the executable to be launched. For auxiliary binaries shipped with the application, one can construct such a path starting with QCoreApplication::applicationDirPath (). Similarly, to explicitly run an executable that is to be found relative to the directory set with setWorkingDirectory (), use a program path starting with "./" or "../" as the case may be.
On Windows, the ".exe" suffix is not required for most uses, except those outlined in the CreateProcess documentation. Additionally, QProcess will convert the Unix-style forward slashes to Windows path backslashes for the program name. This allows code using QProcess to be written in a cross-platform manner, as shown in the examples above.
QProcess does not support directly executing Unix shell or Windows command interpreter built-in functions, such as
cmd.exe
's
dir
command or the Bourne shell's
export
. On Unix, even though many shell built-ins are also provided as separate executables, their behavior may differ from those implemented as built-ins. To run those commands, one should explicitly execute the interpreter with suitable options. For Unix systems, launch "/bin/sh" with two arguments: "-c" and a string with the command-line to be run. For Windows, due to the non-standard way
cmd.exe
parses its command-line, use
setNativeArguments
() (for example, "/c dir d:").
The QProcess API offers methods to manipulate the environment variables that the child process will see. By default, the child process will have a copy of the current process environment variables that exist at the time the start () function is called. This means that any modifications performed using qputenv () prior to that call will be reflected in the child process' environment. Note that QProcess makes no attempt to prevent race conditions with qputenv () happening in other threads, so it is recommended to avoid qputenv () after the application's initial start up.
The environment for a specific child can be modified using the processEnvironment () 和 setProcessEnvironment () functions, which use the QProcessEnvironment class. By default, processEnvironment () will return an object for which QProcessEnvironment::inheritsFromParent () is true. Setting an environment that does not inherit from the parent will cause QProcess to use exactly that environment for the child when it is started.
The normal scenario starts from the current environment by calling QProcessEnvironment::systemEnvironment () and then proceeds to adding, changing, or removing specific variables. The resulting variable roster can then be applied to a QProcess with setProcessEnvironment ().
It is possible to remove all variables from the environment or to start from an empty environment, using the QProcessEnvironment() default constructor. This is not advisable outside of controlled and system-specific conditions, as there may be system variables that are set in the current process environment and are required for proper execution of the child process.
On Windows, QProcess will copy the current process'
"PATH"
and
"SystemRoot"
environment variables if they were unset. It is not possible to unset them completely, but it is possible to set them to empty values. Setting
"PATH"
to empty on Windows will likely cause the child process to fail to start.
進程有 2 個預定義輸齣通道:標準輸齣通道 (
stdout
) 供給常規控製颱輸齣,和標準錯誤通道 (
stderr
) 通常提供由進程打印的錯誤。這些通道錶示 2 個單獨數據流。可以在它們之間切換通過調用
setReadChannel
()。QProcess 發射
readyRead
() 當當前讀取通道數據可用時。它還發射
readyReadStandardOutput
() 當新標準輸齣數據可用時,和當新標準錯誤數據可用時,
readyReadStandardError
() 發射。代替調用
read
(),
readLine
(),或
getChar
(),可以明確讀取 2 通道之一的所有數據通過調用
readAllStandardOutput
() 或
readAllStandardError
().
通道術語可能産生誤導。注意,進程的輸齣通道對應於 QProcess 的 read 通道,而進程的輸入通道對應於 QProcess 的 write 通道。這是因為我們使用 QProcess 讀取的是進程的輸齣,而寫入的變為進程的輸入。
QProcess 可以閤並 2 輸齣通道,以便來自運行進程的標準輸齣和標準錯誤數據均使用標準輸齣通道。調用 setProcessChannelMode () 采用 MergedChannels 在開始激活此特徵的進程之前。還有將正運行進程輸齣轉發到調用主進程的選項,通過傳遞 ForwardedChannels 作為自變量。隻轉發某個輸齣通道是可能的 - 通常會使用 ForwardedErrorChannel ,但 ForwardedOutputChannel 也存在。注意,在 GUI 應用程序中使用通道轉發通常是個壞主意 - 應該以圖形呈現錯誤取而代之。
某些進程需要特殊環境設置纔能運轉。可以為進程設置環境變量通過調用 setProcessEnvironment ()。要設置工作目錄,調用 setWorkingDirectory ()。默認情況下,進程在調用進程的當前工作目錄下運行。
屬於以 QProcess 啓動的 GUI 應用程序的窗口的定位和屏幕 Z 次序,由底層窗口係統控製。對於 Qt 5 應用程序,可以指定定位使用
-qwindowgeometry
命令行選項;X11 應用程序一般接受
-geometry
命令行選項。
QProcess 提供允許在沒有事件循環的情況下使用的一組函數,通過掛起調用綫程直到某些信號被發射為止:
從主綫程調用這些函數 (綫程調用 QApplication::exec ()) 可能導緻用戶界麵被凍結。
以下範例運行
gzip
以壓縮字符串 Qt rocks!,沒有事件循環:
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();
另請參閱 QBuffer , QFile ,和 QTcpSocket .
注意: 此 typedef 隻可用於桌麵 Windows。
在 Windows,
QProcess
使用 Win32 API 函數
CreateProcess
去啓動子級進程。而
QProcess
提供啓動進程的舒適方式而無需擔心平颱細節,在某些情況下調優是可取的將參數傳遞給
CreateProcess
。這被履行通過定義
CreateProcessArgumentModifier
函數並把它傳遞給
setCreateProcessArgumentsModifier
.
A
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 ().
此枚舉描述不同退齣狀態為 QProcess .
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::NormalExit
|
0
|
進程正常退齣。 |
QProcess::CrashExit
|
1
|
進程崩潰。 |
另請參閱 exitStatus ().
此枚舉描述進程輸入通道模式為 QProcess 。將這些值之一傳遞給 setInputChannelMode () 去設置當前寫入通道模式。
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::ManagedInputChannel
|
0
|
QProcess 管理正運行進程的輸入。這是默認輸入通道模式為 QProcess . |
QProcess::ForwardedInputChannel
|
1
|
QProcess 把主進程輸入轉發給正運行進程。子級進程從主進程的相同源讀取其標準輸入。注意:主進程不得試著讀取其標準輸入 (當子級進程正運行時)。 |
另請參閱 setInputChannelMode ().
此枚舉描述正運行進程所使用的進程通道。傳遞這些值之一給 setReadChannel () 設置當前讀取通道為 QProcess .
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::StandardOutput
|
0
|
正運行進程的 stdout (標準輸齣)。 |
QProcess::StandardError
|
1
|
正運行進程的 stderr (標準錯誤)。 |
另請參閱 setReadChannel ().
此枚舉描述進程的輸齣通道模式為 QProcess 。將這些值之一傳遞給 setProcessChannelMode () 以設置當前讀取通道模式。
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::SeparateChannels
|
0
|
QProcess 管理正運行進程的輸齣,將標準輸齣和標準錯誤數據保持在單獨內部緩衝中。可以選擇 QProcess 的當前讀取通道通過調用 setReadChannel ()。這是默認通道模式對於 QProcess . |
QProcess::MergedChannels
|
1
|
QProcess
將在運行進程的輸齣閤並到標準輸齣通道 (
stdout
)。標準錯誤通道 (
stderr
) 將不接收任何數據。運行進程的標準輸齣和標準錯誤數據是交錯的。對於分離進程,正運行進程的閤並輸齣被轉發到主進程。
|
QProcess::ForwardedChannels
|
2
|
QProcess 將正運行進程的輸齣轉發到主進程。由子級進程寫入其標準輸齣和標準錯誤的任何內容,都將寫入主進程的標準輸齣和標準錯誤。 |
QProcess::ForwardedErrorChannel
|
4
|
QProcess 管理在運行進程的標準輸齣,但會將標準錯誤轉發到主進程。這反映將命令行工具作為過濾器的典型用法,其中標準輸齣被重定嚮到另一進程 (或文件),而標準錯誤被打印到控製颱為診斷目的 (該值在 Qt 5.2 引入)。 |
QProcess::ForwardedOutputChannel
|
3
|
與 ForwardedErrorChannel 互補 (該值在 Qt 5.2 引入)。 |
注意: Windows 有意抑製從僅 GUI 應用程序輸齣到繼承控製颱。這 not 適用於重定嚮到文件或管道的輸齣。盡管如此,要在控製颱轉發僅 GUI 應用程序的輸齣,必須使用 SeparateChannels 和通過讀取輸齣並將其寫入適當輸齣通道自己來履行轉發。
另請參閱 setProcessChannelMode ().
此枚舉描述錯誤的不同類型,報告通過 QProcess .
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::FailedToStart
|
0
|
進程啓動失敗。被援引的程序丟失,或可能沒有足夠權限 (或資源) 援引程序。 |
QProcess::Crashed
|
1
|
進程有時崩潰在成功啓動後。 |
QProcess::Timedout
|
2
|
最後 waitFor...() 函數超時。狀態對於 QProcess 不變,和可以再次試著調用 waitFor...()。 |
QProcess::WriteError
|
4
|
發生錯誤當試圖寫入進程時。例如,進程可能未運行,或它可能已關閉其輸入通道。 |
QProcess::ReadError
|
3
|
發生錯誤當試圖從進程讀取時。例如,進程可能未運行。 |
QProcess::UnknownError
|
5
|
發生未知錯誤。這是默認返迴值為 error (). |
另請參閱 error ().
此枚舉描述不同狀態為 QProcess .
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::NotRunning
|
0
|
進程未運行。 |
QProcess::Starting
|
1
|
進程正在啓動,但尚未援引程序。 |
QProcess::Running
|
2
|
進程正在運行且讀寫就緒。 |
另請參閱 state ().
[since 6.6]
enum class QProcess::
UnixProcessFlag
這些標誌可以用於
flags
field of
UnixProcessParameters
.
| 常量 | 值 | 描述 |
|---|---|---|
QProcess::UnixProcessFlag::CloseFileDescriptors
|
0x0010
|
Close all file descriptors above the threshold defined by
lowestFileDescriptorToClose
, preventing any currently open descriptor in the parent process from accidentally leaking to the child. The
stdin
,
stdout
,和
stderr
file descriptors are never closed.
|
QProcess::UnixProcessFlag::CreateNewSession (since Qt 6.7)
|
0x0040
|
Starts a new process session, by calling
setsid(2)
. This allows the child process to outlive the session the current process is in. This is one of the steps that
startDetached
() takes to allow the process to detach, and is also one of the steps to daemonize a process.
|
QProcess::UnixProcessFlag::DisconnectControllingTerminal (since Qt 6.7)
|
0x0080
|
Requests that the process disconnect from its controlling terminal, if it has one. If it has none, nothing happens. Processes still connected to a controlling terminal may get a Hang Up (
SIGHUP
) signal if the terminal closes, or one of the other terminal-control signals (
SIGTSTP
,
SIGTTIN
,
SIGTTOU
). Note that on some operating systems, a process may only disconnect from the controlling terminal if it is the session leader, meaning the
CreateNewSession
flag may be required. Like it, this is one of the steps to daemonize a process.
|
QProcess::UnixProcessFlag::IgnoreSigPipe
|
0x0002
|
Always sets the
SIGPIPE
signal to ignored (
SIG_IGN
), even if the
ResetSignalHandlers
flag was set. By default, if the child attempts to write to its standard output or standard error after the respective channel was closed with
QProcess::closeReadChannel
(), it would get the
SIGPIPE
signal and terminate immediately; with this flag, the write operation fails without a signal and the child may continue executing.
|
QProcess::UnixProcessFlag::ResetIds (since Qt 6.7)
|
0x0100
|
Drops any retained, effective user or group ID the current process may still have (see
setuid(2)
and
setgid(2)
, plus
QCoreApplication::setSetuidAllowed
()). This is useful if the current process was setuid or setgid and does not wish the child process to retain the elevated privileges.
|
QProcess::UnixProcessFlag::ResetSignalHandlers
|
0x0001
|
Resets all Unix signal handlers back to their default state (that is, pass
SIG_DFL
to
signal(2)
). This flag is useful to ensure any ignored (
SIG_IGN
) signal does not affect the child's behavior.
|
QProcess::UnixProcessFlag::UseVFork
|
0x0020
|
請求
QProcess
使用
vfork(2)
to start the child process. Use this flag to indicate that the callback function set with
setChildProcessModifier
() is safe to execute in the child side of a
vfork(2)
; that is, the callback does not modify any non-local variables (directly or through any function it calls), nor attempts to communicate with the parent process. It is implementation-defined if
QProcess
will actually use
vfork(2)
and if
vfork(2)
is different from standard
fork(2)
.
|
QProcess::UnixProcessFlag::DisableCoreDumps (since Qt 6.9)
|
0x0200
|
請求 QProcess disable core dumps in the child process. This is useful if the executable being run is likely to crash but users and maintainers are going to be uninterested in generating bug reports for those conditions (for example, the executable is a test process). This setting does not affect the exitStatus () of the crashed process. It is implemented by setting the core dump size resource soft limit to zero, meaning the application can still reverse this change by raising it to a value up to the hard limit. |
該枚舉在 Qt 6.6 引入。
UnixProcessFlags 類型是 typedef 對於 QFlags <UnixProcessFlag>. It stores an OR combination of UnixProcessFlag values.
另請參閱 setUnixProcessParameters () 和 unixProcessParameters ().
[explicit]
QProcess::
QProcess
(
QObject
*
parent
= nullptr)
構造 QProcess 對象采用給定 parent .
[virtual noexcept]
QProcess::
~QProcess
()
銷毀 QProcess 對象,即:殺除進程。
注意:此函數不會返迴直到進程被終止。
返迴上次啓動進程采用的命令行自變量。
另請參閱 setArguments () 和 start ().
[override virtual]
qint64
QProcess::
bytesToWrite
() const
重實現: QIODevice::bytesToWrite () const.
[since 6.0]
std::function
<
void
()> QProcess::
childProcessModifier
() const
返迴先前設置的修飾符函數通過調用 setChildProcessModifier ().
注意: 此函數隻可用於 Unix 平颱。
該函數在 Qt 6.0 引入。
另請參閱 setChildProcessModifier () 和 unixProcessParameters ().
[override virtual]
void
QProcess::
close
()
重實現: QIODevice::close ().
關閉進程的所有通信並殺除它。在調用此函數後, QProcess 將不再發射 readyRead (),且無法再讀取或寫入數據。
關閉讀取通道 channel 。在調用此函數後, QProcess 將不再接收通道數據。任何已收到的數據仍可用於讀取。
調用此函數以節省內存,若對進程的輸齣不感興趣。
另請參閱 closeWriteChannel () 和 setReadChannel ().
調度寫入通道對於 QProcess 要被關閉。一旦所有數據被寫入進程,通道就將關閉。在調用此函數後,任何寫入進程的試圖都將失敗。
關閉寫入通道是必要的,對於讀取輸入數據 (直到通道被關閉為止) 的程序而言。例如,程序 more 用於在 Unix 和 Windows 控製颱中顯示文本數據。但它不會顯示文本數據直到 QProcess 的寫入通道被關閉。範例:
QProcess more; more.start("more"); more.write("Text to display"); more.closeWriteChannel(); // QProcess will emit readyRead() once "more" starts printing
寫入通道被隱式打開當 start () 被調用。
另請參閱 closeReadChannel ().
返迴先前設置的
CreateProcess
修飾符函數。
注意: 此函數隻可用於 Windows 平颱。
另請參閱 setCreateProcessArgumentsModifier () 和 QProcess::CreateProcessArgumentModifier .
返迴最後齣現的錯誤類型。
另請參閱 state ().
[signal]
void
QProcess::
errorOccurred
(
QProcess::ProcessError
error
)
此信號被發射,當進程齣現錯誤時。指定 error 描述齣現的錯誤類型。
[static]
int
QProcess::
execute
(const
QString
&
program
, const
QStringList
&
arguments
= {})
啓動程序 program 采用自變量 arguments 在新進程中,等待它完成,然後返迴進程的退齣代碼。新進程寫入控製颱的任何數據會被轉發給調用進程。
環境和工作目錄繼承自調用進程。
自變量處理分彆等同 start () 重載。
若進程無法啓動,返迴 -2。若進程崩潰,返迴 -1。否則,返迴進程的退齣代碼。
另請參閱 start ().
返迴最後完成進程的退齣代碼。
此值無效除非 exitStatus () 返迴 NormalExit .
返迴最後完成的進程退齣狀態。
在 Windows,若進程被另一應用程序的 TerminateProcess() 所終止,此函數仍會返迴 NormalExit 除非退齣代碼小於 0。
[noexcept, since 6.7]
void
QProcess::
failChildProcessModifier
(const
char
*
描述
,
int
error
= 0)
This functions can be used inside the modifier set with
setChildProcessModifier
() to indicate an error condition was encountered. When the modifier calls these functions,
QProcess
將發射
errorOccurred
() with code
QProcess::FailedToStart
in the parent process. The
description
can be used to include some information in
errorString
() to help diagnose the problem, usually the name of the call that failed, similar to the C Library function
perror()
。此外,
error
參數可以是
<errno.h>
error code whose text form will also be included.
For example, a child modifier could prepare an extra file descriptor for the child process this way:
process.setChildProcessModifier([fd, &process]() { if (dup2(fd, TargetFileDescriptor) < 0) process.failChildProcessModifier(errno, "aux comm channel"); }); process.start();
Where
fd
is a file descriptor currently open in the parent process. If the
dup2()
system call resulted in an
EBADF
condition, the process
errorString
() could be "Child process modifier reported error: aux comm channel: Bad file descriptor".
This function does not return to the caller. Using it anywhere except in the child modifier and with the correct QProcess object is undefined behavior.
注意: The implementation imposes a length limit to the description parameter to about 500 characters. This does not include the text from the error 代碼。
該函數在 Qt 6.7 引入。
另請參閱 setChildProcessModifier () 和 setUnixProcessParameters ().
[signal]
void
QProcess::
finished
(
int
exitCode
,
QProcess::ExitStatus
exitStatus
= NormalExit)
此信號被發射當進程完成時。 exitCode 是進程的退齣代碼 (僅對正常退齣有效),和 exitStatus 是退齣狀態。在進程完成後,緩衝在 QProcess 仍完好無損。仍可以讀取進程可能已寫入的任何數據在完成之前。
另請參閱 exitStatus ().
返迴通道模式對於 QProcess 標準輸入通道。
另請參閱 setInputChannelMode () 和 InputChannelMode .
[override virtual]
bool
QProcess::
isSequential
() const
重實現: QIODevice::isSequential () const.
[slot]
void
QProcess::
kill
()
殺除當前進程,導緻它立即退齣。
在 Windows,kill() 使用 TerminateProcess,而在 Unix 和 macOS,把 SIGKILL 信號發送給進程。
另請參閱 terminate ().
返迴程序的附加本機命令行自變量。
注意: 此函數隻可用於 Windows 平颱。
另請參閱 setNativeArguments ().
[static]
QString
QProcess::
nullDevice
()
操作係統的 null 設備。
返迴的文件路徑使用本機目錄分隔符。
另請參閱 QProcess::setStandardInputFile (), QProcess::setStandardOutputFile (),和 QProcess::setStandardErrorFile ().
[override virtual]
bool
QProcess::
open
(
QIODeviceBase::OpenMode
mode
= ReadWrite)
重實現: QIODevice::open (QIODeviceBase::OpenMode mode).
啓動程序設置通過 setProgram () 采用自變量設置通過 setArguments ()。OpenMode 被設為 mode .
此方法是彆名化的 start (),且存在僅為完全實現定義接口通過 QIODevice .
返迴
true
若程序已啓動。
另請參閱 start (), setProgram (),和 setArguments ().
返迴通道模式對於 QProcess 標準輸齣和標準錯誤通道。
另請參閱 setProcessChannelMode (), ProcessChannelMode ,和 setReadChannel ().
返迴環境從 QProcess 將它傳遞給子級進程。若未設置環境使用 setProcessEnvironment (),此方法返迴指示環境將繼承自父級的對象。
另請參閱 setProcessEnvironment (), QProcessEnvironment::inheritsFromParent (),和 環境變量 .
返迴正在運行進程的本機進程標識符,若可用。若目前沒有進程正在運行,
0
被返迴。
返迴進程最後一次啓動時采用的程序。
另請參閱 setProgram () 和 start ().
不管當前讀取通道,此函數從進程標準錯誤返迴所有可用數據按 QByteArray .
另請參閱 readyReadStandardError (), readAllStandardOutput (), readChannel (),和 setReadChannel ().
不管當前讀取通道,此函數從進程標準輸齣返迴所有可用數據按 QByteArray .
另請參閱 readyReadStandardOutput (), readAllStandardError (), readChannel (),和 setReadChannel ().
返迴當前讀取通道為 QProcess .
另請參閱 setReadChannel ().
[override virtual protected]
qint64
QProcess::
readData
(
char
*
data
,
qint64
maxlen
)
重實現: QIODevice::readData (char *data, qint64 maxSize).
[private signal]
void
QProcess::
readyReadStandardError
()
此信號被發射當進程已使新數據可用透過其標準錯誤通道 (
stderr
)。它被發射不管當前
讀取通道
.
注意: 這是私有信號。它可以用於信號連接,但不能由用戶發射。
另請參閱 readAllStandardError () 和 readChannel ().
[private signal]
void
QProcess::
readyReadStandardOutput
()
此信號被發射當進程已使新數據可用透過其標準輸齣通道 (
stdout
)。它被發射不管當前
讀取通道
.
注意: 這是私有信號。它可以用於信號連接,但不能由用戶發射。
另請參閱 readAllStandardOutput () 和 readChannel ().
設置 arguments 以傳遞給被調用程序當啓動進程時。必須調用此函數先於 start ().
另請參閱 start (), setProgram (),和 arguments ().
[since 6.0]
void
QProcess::
setChildProcessModifier
(const
std::function
<
void
()> &
modifier
)
設置
modifier
函數為子級進程,對於 Unix 係統 (包括 macOS;對於 Windows,見
setCreateProcessArgumentsModifier
())。函數包含通過
modifier
自變量,會在子級進程中被援引後於
fork()
or
vfork()
已完成且
QProcess
有為子級進程設置標準文件描述符,但先於
execve()
,在
start
().
以下展示範例,設置無特權運行子級進程:
void runSandboxed(const QString &name, const QStringList &arguments) { QProcess proc; proc.setChildProcessModifier([] { // Drop all privileges in the child process, and enter // a chroot jail. ::setgroups(0, nullptr); ::chroot("/run/safedir"); ::chdir("/"); ::setgid(safeGid); ::setuid(safeUid); ::umask(077); }); proc.start(name, arguments); proc.waitForFinished(); }
If the modifier function experiences a failure condition, it can use
failChildProcessModifier
() to report the situation to the
QProcess
caller. Alternatively, it may use other methods of stopping the process, like
_exit()
,或
abort()
.
Certain properties of the child process, such as closing all extraneous file descriptors or disconnecting from the controlling TTY, can be more readily achieved by using setUnixProcessParameters (), which can detect failure and report a FailedToStart condition. The modifier is useful to change certain uncommon properties of the child process, such as setting up additional file descriptors. If both a child process modifier and Unix process parameters are set, the modifier is run before these parameters are applied.
注意: 在多綫程應用程序中,此函數必須小心,不要調用任何可能已用於其它綫程的互斥鎖函數 (一般而言,建議僅使用由 POSIX 定義為 "異步信號安全" 的函數)。大多數 Qt API 在此迴調中都不安全,包括 qDebug (),且可能導緻死鎖。
注意:
If the UnixProcessParameters::UseVFork flag is set via
setUnixProcessParameters
(),
QProcess
可以使用
vfork()
語義來啓動子級進程,因此,該函數必須服從甚至更嚴格的約束。首先,因為它仍然與父級進程共享內存,所以不得將它寫入任何非局部變量,且必須服從正確次序語義 (當讀取它們時),以避免數據競爭。其次,甚至更多庫函數可能行為失常;因此,此函數隻應用於低級係統調用,譬如
read()
,
write()
,
setsid()
,
nice()
,和類似的。
該函數在 Qt 6.0 引入。
另請參閱 childProcessModifier (), failChildProcessModifier (),和 setUnixProcessParameters ().
設置
modifier
為
CreateProcess
Win32 API 調用。傳遞
QProcess::CreateProcessArgumentModifier()
以移除先前設置的。
注意: 此函數隻可用於 Windows 平颱且要求 C++ 11。
另請參閱 createProcessArgumentsModifier (), QProcess::CreateProcessArgumentModifier ,和 setChildProcessModifier ().
設置通道模式為 QProcess 標準輸入通道到 mode 指定。會使用此模式當下次 start () 被調用。
另請參閱 inputChannelMode () 和 InputChannelMode .
設置額外本機命令行 arguments 為程序。
在操作係統中,若係統 API 用於傳遞命令行 arguments 到本機子進程使用單字符串,可以設想無法傳遞命令行憑藉 QProcess 基於列錶的可移植 API。在這種情況下,必須使用此函數來設置字符串, appended 到通常由自變量列錶閤成的字符串,帶定界空格。
注意: 此函數隻可用於 Windows 平颱。
另請參閱 nativeArguments ().
設置通道模式為 QProcess 標準輸齣和標準錯誤通道到 mode 指定。會使用此模式當下次 start () 被調用。例如:
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();
另請參閱 processChannelMode (), ProcessChannelMode ,和 setReadChannel ().
設置 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 環境變量名不區分大小寫。
另請參閱 processEnvironment (), QProcessEnvironment::systemEnvironment (),和 環境變量 .
[protected]
void
QProcess::
setProcessState
(
QProcess::ProcessState
state
)
設置當前狀態為 QProcess 到 state 指定。
另請參閱 state ().
設置 program 為使用當啓動進程時。此函數必須被調用先於 start ().
若
program
是絕對路徑,它指定將要發起的準確可執行文件。相對路徑將以特定平颱方式解析,包括搜索
PATH
環境變量 (見
查找可執行文件
瞭解細節)。
另請參閱 start (), setArguments (), program (),和 QStandardPaths::findExecutable ().
設置當前讀取通道為 QProcess 到給定 channel 。當前輸入通道用於函數 read (), readAll (), readLine (),和 getChar ()。它還確定哪個通道觸發 QProcess 以發射 readyRead ().
另請參閱 readChannel ().
將進程的標準錯誤重定嚮到文件 fileName 。當重定嚮到位時,標準錯誤讀取通道被關閉:讀取它使用 read () 將始終失敗,就像 readAllStandardError ()。文件將被追加若 mode 為 Append,否則, 它將被截取。
見 setStandardOutputFile () 瞭解如何打開文件的更多相關信息。
注意:若 setProcessChannelMode () 被調用采用自變量 QProcess::MergedChannels ,此函數不起作用。
另請參閱 setStandardInputFile (), setStandardOutputFile (),和 setStandardOutputProcess ().
將進程的標準輸入重定嚮到文件指示通過 fileName 。當輸入重定嚮到位時, QProcess 對象將處於隻讀模式 (調用 write () 將導緻齣錯)。
要使進程立即讀取 EOF,傳遞 nullDevice () 在此。這更清潔比使用 closeWriteChannel () 在寫入任何數據之前,因為在啓動進程之前可以設置它。
若文件 fileName 不存在此刻 start () 被調用或不可讀,啓動進程將失敗。
在進程啓動後調用 setStandardInputFile() 不起作用。
另請參閱 setStandardOutputFile (), setStandardErrorFile (),和 setStandardOutputProcess ().
將進程的標準輸齣重定嚮到文件 fileName 。當重定嚮到位時,標準輸齣讀取通道被關閉:讀取它使用 read () 將始終失敗,就像 readAllStandardOutput ().
要丟棄來自進程的所有標準輸齣,傳遞 nullDevice () 在此。這比簡單從不讀取標準輸齣更高效,因為沒有 QProcess 緩衝被填充。
若文件 fileName 不存在此刻 start () 被調用,它將被創建。若它無法被創建,啓動將失敗。
若文件存在且 mode is QIODeviceBase::Truncate , the file will be truncated. Otherwise (if mode is QIODeviceBase::Append ), the file will be appended to.
在進程啓動後調用 setStandardOutputFile() 不起作用。
若 fileName 為空字符串,它停止重定嚮標準輸齣。這對重定嚮後,還原標準輸齣很有用。
另請參閱 setStandardInputFile (), setStandardErrorFile (),和 setStandardOutputProcess ().
將此進程的標準輸齣流管道到 destination 進程的標準輸入。
以下 Shell 命令:
command1 | command2
可以施行采用 QProcess 通過以下代碼:
QProcess process1; QProcess process2; process1.setStandardOutputProcess(&process2); process1.start("command1"); process2.start("command2");
[since 6.6]
void
QProcess::
setUnixProcessParameters
(const
QProcess::UnixProcessParameters
&
params
)
把 Unix 係統子進程的額外設置和參數設為 params 。此函數可以用於要求 QProcess 修改子級進程,在發起目標可執行文件之前。
This function can be used to change certain properties of the child process, such as closing all extraneous file descriptors, changing the nice level of the child, or disconnecting from the controlling TTY. For more fine-grained control of the child process or to modify it in other ways, use the setChildProcessModifier () function. If both a child process modifier and Unix process parameters are set, the modifier is run before these parameters are applied.
注意: 此函數隻可用於 Unix 平颱。
該函數在 Qt 6.6 引入。
另請參閱 unixProcessParameters () 和 setChildProcessModifier ().
[since 6.6]
void
QProcess::
setUnixProcessParameters
(
QProcess::UnixProcessFlags
flagsOnly
)
Sets the extra settings for the child process on Unix systems to
flagsOnly
. This is the same as the overload with just the
flags
field set.
注意: 此函數隻可用於 Unix 平颱。
這是重載函數。
該函數在 Qt 6.6 引入。
另請參閱 unixProcessParameters () 和 setChildProcessModifier ().
把工作目錄設為 dir . QProcess 將在此目錄下啓動進程。默認行為是在調用進程的工作目錄下啓動進程。
另請參閱 workingDirectory () 和 start ().
[static]
QStringList
QProcess::
splitCommand
(
QStringView
command
)
分割字符串 command 成令牌列錶,並返迴列錶。
帶空格的令牌可以由雙引號環繞;3 連續雙引號錶示引號字符本身。
啓動給定 program 在新進程中,傳遞的命令行自變量在 arguments 。見 setProgram () 瞭解有關信息對於如何 QProcess searches for the executable to be run. The OpenMode is set to mode . No further splitting of the arguments is performed.
The QProcess 對象將立即進入 Starting 狀態。若進程成功啓動, QProcess 將發射 started ();否則, errorOccurred () will be emitted. Do note that on platforms that are able to start child processes synchronously (notably Windows), those signals will be emitted before this function returns and this QProcess object will transition to either QProcess::Running or QProcess::NotRunning state, respectively. On others paltforms, the started () 和 errorOccurred () signals will be delayed.
調用 waitForStarted () to make sure the process has started (or has failed to start) and those signals have been emitted. It is safe to call that function even if the process starting state is already known, though the signal will not be emitted again.
Windows:
自變量加引號並被拼接到兼容命令行采用
CommandLineToArgvW()
Windows 函數。對於有不同命令行要求加引號的程序,需要使用
setNativeArguments
()。值得注意的是程序不遵循
CommandLineToArgvW()
規則是 cmd.exe,因此是所有批處理腳本。
若 QProcess 對象已在運行進程,可能在控製颱打印警告,且現有進程將不受影響地繼續運行。
注意: Success at starting the child process only implies the operating system has successfully created the process and assigned the resources every process has, such as its process ID. The child process may crash or otherwise fail very early and thus not produce its expected output. On most operating systems, this may include dynamic linking errors.
另請參閱 processId (), started (), waitForStarted (),和 setNativeArguments ().
啓動程序設置通過 setProgram () 采用自變量設置通過 setArguments ()。OpenMode 被設為 mode .
這是重載函數。
另請參閱 open (), setProgram (),和 setArguments ().
[since 6.0]
void
QProcess::
startCommand
(const
QString
&
command
,
QIODeviceBase::OpenMode
mode
= ReadWrite)
啓動命令 command 在新進程中。OpenMode 被設為 mode .
command 是包含程序名稱及其自變量的單文本字符串。自變量由一個或多個空格分隔。例如:
QProcess process; process.startCommand("del /s *.txt"); // same as process.start("del", QStringList() << "/s" << "*.txt"); ...
必須引用包含空格的自變量纔能被正確提供給新進程。例如:
QProcess process; process.startCommand("dir \"My Documents\"");
文字引號在 command 字符串由 3 引號錶示。例如:
QProcess process; process.startCommand("dir \"Epic 12\"\"\" Singles\"");
之後 command 字符串被拆分並取消引號,此函數的行為像 start ().
在將命令行自變量傳遞給子進程的本機係統 API 使用單字符串的 Windows 操作係統,可以設想無法傳遞命令行憑藉 QProcess 的基於列錶的可移植 API。在這些罕見情況下,需要使用 setProgram () 和 setNativeArguments () 而不是此函數。
該函數在 Qt 6.0 引入。
另請參閱 splitCommand () 和 start ().
啓動程序設置通過
setProgram
() 采用自變量設置通過
setArguments
() 在新進程中,並與之分離。返迴
true
當成功時;否則返迴
false
。若調用進程退齣,分離進程將不受影響地繼續運行。
Unix: 啓動進程將在它自己的會話中運行,且行動像守護程序。
進程將在指定目錄下啓動設置通過 setWorkingDirectory ()。若 workingDirectory () 為空,工作目錄繼承自調用進程。
若函數成功,那麼 * pid 被設為啓動進程的進程標識符;否則,它被設為 -1。注意,子級進程可能退齣,且 PID 可能在沒有通知的情況下失效。此外,在子級進程退齣後,同一 PID 可能被完全不同進程迴收和使用。用戶代碼應小心當使用此變量時,特彆是若某人打算通過操作係統手段強製終止進程。
startDetached() 僅支持以下屬性 setter:
所有其它特性對於 QProcess 對象被忽略。
注意: 被調用進程繼承調用進程的控製颱窗口。要抑製控製颱輸齣,請將標準/錯誤輸齣重定嚮到 QProcess::nullDevice ().
另請參閱 start () 和 startDetached (const QString &program, const QStringList &arguments, const QString &workingDirectory, qint64 *pid).
[static]
bool
QProcess::
startDetached
(const
QString
&
program
, const
QStringList
&
arguments
= {}, const
QString
&
workingDirectory
= QString(),
qint64
*
pid
= nullptr)
啓動程序
program
采用自變量
arguments
按新進程中,並與之分離。返迴
true
當成功時;否則返迴
false
。若調用進程退齣,分離進程將不受影響地繼續運行。
自變量處理分彆等同 start () 重載。
進程將被啓動在目錄 workingDirectory 。若 workingDirectory 為空,工作目錄繼承自調用進程。
若函數成功,那麼 * pid 被設為啓動進程的進程標識符。
此函數重載 QProcess::startDetached ().
另請參閱 start ().
[private signal]
void
QProcess::
started
()
此信號發射由 QProcess 當此過程已開始,且 state () 返迴 運行 .
注意: 這是私有信號。它可以用於信號連接,但不能由用戶發射。
返迴進程的當前狀態。
另請參閱 stateChanged () 和 error ().
[private signal]
void
QProcess::
stateChanged
(
QProcess::ProcessState
newState
)
此信號發射每當狀態對於 QProcess 改變。 newState 自變量為狀態 QProcess 要改變。
注意: 這是私有信號。它可以用於信號連接,但不能由用戶發射。
[static]
QStringList
QProcess::
systemEnvironment
()
以 key=value 對列錶形式返迴調用進程的環境。範例:
QStringList environment = QProcess::systemEnvironment(); // environment = {"PATH=/usr/bin:/usr/local/bin", // "USER=greg", "HOME=/home/greg"}
此函數不緩存係統環境。因此,獲得環境的更新版本是可能的,若低級 C 庫函數像
setenv
or
putenv
有被調用。
不管怎樣,注意,重復調用此函數將重新創建環境變量列錶 (非通俗操作)。
注意: 對於新代碼,推薦使用 QProcessEnvironment::systemEnvironment ()
另請參閱 QProcessEnvironment::systemEnvironment () 和 setProcessEnvironment ().
[slot]
void
QProcess::
terminate
()
試圖終止進程。
進程可能不會因調用此函數而退齣 (它有機會提示用戶是否有未保存的文件,等等)。
在 Windows,terminate() 將 WM_CLOSE 消息張貼到進程的所有頂層窗口,然後張貼到進程本身的主綫程。在 Unix 和 macOS,
SIGTERM
信號被發送。
不運行事件循環的 Windows 控製颱應用程序 (或其事件循環不處理 WM_CLOSE 消息),隻可被終止通過調用 kill ().
另請參閱 kill ().
[noexcept, since 6.6]
QProcess::UnixProcessParameters
QProcess::
unixProcessParameters
() const
返迴 UnixProcessParameters object describing extra flags and settings that will be applied to the child process on Unix systems. The default settings correspond to a default-constructed UnixProcessParameters .
注意: 此函數隻可用於 Unix 平颱。
該函數在 Qt 6.6 引入。
另請參閱 setUnixProcessParameters () 和 childProcessModifier ().
[override virtual]
bool
QProcess::
waitForBytesWritten
(
int
msecs
= 30000)
重實現: QIODevice::waitForBytesWritten (int msecs).
阻塞直到進程已完成且 finished () 信號已發射,或直到 msecs 毫秒已過去。
返迴
true
若進程已完成;否則返迴
false
(若操作超時,若發生錯誤,或者若此
QProcess
已完成)。
可以在沒有事件循環的情況下操作此函數。它很有用,當編寫非 GUI 應用程序和在非 GUI 綫程中履行 I/O 操作時。
警告: 從主 GUI 綫程調用此函數可能導緻用戶界麵被凍結。
若 msecs 為 -1,此函數不會超時。
另請參閱 finished (), waitForStarted (), waitForReadyRead (),和 waitForBytesWritten ().
[override virtual]
bool
QProcess::
waitForReadyRead
(
int
msecs
= 30000)
重實現: QIODevice::waitForReadyRead (int msecs).
阻塞直到進程啓動且 started () 信號已發射,或直到 msecs 毫秒已過去。
返迴
true
若進程成功啓動;否則返迴
false
(若操作超時或齣現錯誤)。若進程已經成功啓動在此函數之前,它會立即返迴。
可以在沒有事件循環的情況下操作此函數。它很有用,當編寫非 GUI 應用程序和在非 GUI 綫程中履行 I/O 操作時。
警告: 從主 GUI 綫程調用此函數可能導緻用戶界麵被凍結。
若 msecs 為 -1,此函數不會超時。
另請參閱 started (), waitForReadyRead (), waitForBytesWritten (),和 waitForFinished ().
若 QProcess 已賦值工作目錄,此函數返迴工作目錄 QProcess 將在程序開始之前進入。否則,返迴空字符串 (即:沒有賦值目錄),且 QProcess 將使用應用程序的當前工作目錄取而代之。
另請參閱 setWorkingDirectory ().