在Linux中,wait
函数和waitpid
函数都是用来等待子进程结束并获取子进程的终止状态的。
wait
函数的函数原型如下:
#include#include pid_t wait(int *status);
wait
函数会等待任意一个子进程结束,并将子进程的终止状态保存在status
指向的整型变量中。如果不关心子进程的终止状态,可以将status
设为NULL
。wait
函数返回被终止子进程的进程ID。
示例代码如下:
#include#include #include #include #include int main() { pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // 子进程执行的代码 printf("Child process\n"); sleep(3); exit(0); } else { // 父进程执行的代码 printf("Parent process\n"); int status; pid_t child_pid = wait(&status); if (WIFEXITED(status)) { printf("Child process %d exited normally with status %d\n", child_pid, WEXITSTATUS(status)); } else { printf("Child process %d exited abnormally\n", child_pid); } } return 0; }
输出结果:
Parent process Child process Child process 1234 exited normally with status 0
waitpid
函数的函数原型如下:
#include#include pid_t waitpid(pid_t pid, int *status, int options);
waitpid
函数可以指定等待的子进程ID,其中pid
参数有以下几种取值:
pid > 0
:等待进程ID为pid
的子进程;pid = -1
:等待任意一个子进程;pid = 0
:等待和调用waitpid
函数的父进程在同一个进程组的任意子进程;pid < -1
:等待进程组ID为-pid
的任意子进程。
status
参数和wait
函数一样,用来保存子进程的终止状态。
options
参数用来指定额外的选项,比如可以使用WNOHANG
选项来非阻塞地等待子进程结束。
示例代码如下:
#include#include #include #include #include int main() { pid_t pid = fork(); if (pid == -1) { perror("fork"); exit(1); } else if (pid == 0) { // 子进程执行的代码 printf("Child process\n"); sleep(3); exit(0); } else { // 父进程执行的代码 printf("Parent process\n"); int status; pid_t child_pid = waitpid(pid, &status, 0); if (WIFEXITED(status)) { printf("Child process %d exited normally with status %d\n", child_pid, WEXITSTATUS(status)); } else { printf("Child process %d exited abnormally\n", child_pid); } } return 0; }
输出结果和前面的例子是一样的。