阅读量:138
wifexited和waitpid函数可以一起使用来等待子进程的退出状态,并且获取子进程的退出状态信息。
具体步骤如下:
- 使用fork函数创建子进程
- 在父进程中使用waitpid函数来等待子进程的退出状态
- 在waitpid函数中传入WIFEXITED选项来检查子进程是否正常退出
- 使用WEXITSTATUS宏来获取子进程的退出状态信息
示例代码如下:
#include
#include
#include
#include
#include
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork error");
exit(-1);
} else if (pid == 0) {
// 子进程
printf("Child process is running\n");
exit(0);
} else {
// 父进程
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child process exited normally with status: %d\n", WEXITSTATUS(status));
}
}
return 0;
}
在上面的示例代码中,父进程通过waitpid函数等待子进程的退出状态,并通过WIFEXITED和WEXITSTATUS来获取子进程的退出状态信息。