waitpid

C语言waitpid函数怎么使用

小亿
103
2023-07-07 21:12:57
栏目: 编程语言

waitpid函数用于等待指定的子进程终止,并获取子进程的状态信息。

waitpid函数的原型如下:

#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);

参数说明:

返回值:

使用示例:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
int status;
pid = fork(); // 创建子进程
if (pid < 0) {
perror("fork error");
exit(1);
} else if (pid == 0) {
// 子进程执行的代码
printf("Child process: pid=%d, ppid=%d\n", getpid(), getppid());
sleep(2);
exit(0);
} else {
// 父进程执行的代码
printf("Parent process: pid=%d, childPid=%d\n", getpid(), pid);
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child process exited normally with status: %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Child process terminated by signal: %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("Child process stopped by signal: %d\n", WSTOPSIG(status));
}
}
return 0;
}

在上述示例中,父进程通过fork创建了一个子进程,子进程打印自己的进程ID和父进程ID,并在2秒后退出。父进程等待子进程退出,并获取子进程的状态信息。使用waitpid函数时,传入子进程ID和status变量的地址,等待子进程退出后,通过WIFEXITED、WIFSIGNALED、WIFSTOPPED等宏判断子进程的终止方式,并打印相应的信息。

0
看了该问题的人还看了