溫馨提示×

C++的wifexited函數(shù)怎么使用

小億
318
2023-08-08 04:44:42
欄目: 編程語言

在C++中,wifexited函數(shù)是一個宏,用于檢查子進程是否正常退出。該宏接受一個表示子進程狀態(tài)的整數(shù)參數(shù),并返回一個非零值(真)表示子進程正常退出,返回0(假)表示子進程不是正常退出。

下面是一個使用wifexited函數(shù)的示例代碼:

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
int main() {
pid_t childPid = fork();
if (childPid == 0) {
// 子進程
std::cout << "This is child process." << std::endl;
sleep(2);  // 模擬子進程工作
exit(0);  // 子進程正常退出
} else if (childPid > 0) {
// 父進程
int status;
waitpid(childPid, &status, 0);  // 等待子進程退出
if (WIFEXITED(status)) {
std::cout << "Child process exited normally." << std::endl;
} else {
std::cout << "Child process did not exit normally." << std::endl;
}
} else {
std::cerr << "Fork failed." << std::endl;
return 1;
}
return 0;
}

上述代碼中,首先使用fork函數(shù)創(chuàng)建了一個子進程。子進程輸出一條信息后,使用exit(0)正常退出。父進程使用waitpid函數(shù)等待子進程退出,并使用WIFEXITED宏判斷子進程是否正常退出。最后,根據(jù)WIFEXITED的返回值輸出相應的消息。

當運行上述代碼時,子進程會等待2秒鐘后退出,父進程會輸出Child process exited normally.的消息。

0