#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus); //等待任意子进程结束,并给子进程收尸
参数: 获取子进程退出状态,NULL则表示忽略子进程退出状态
返回值:
成功: 收尸的子进程的进程号
失败: -1, 并设置errno
WIFEXITED(wstatus) --- 当子进程正常退出时,返回为真
WEXITSTATUS(wstatus) --- 当子进程正常退出时,返回子进程退出值
pid_t waitpid(pid_t pid, int *wstatus, int options); //功能:等待指定的子进程结束,并收尸(阻塞和非阻塞)
参数:
pid:
>0: 只等待进程ID等于pid的子进程
0:等待其组ID等于调用进程的组ID的任一子进程。
<-1:等待其组ID等于pid的绝对值的任一子进程。
wstatus:同wait
options:
WNOHANG:若由pid指定的子进程没有退出,则waitpid不阻塞,此时返回值为0
0: 同wait
返回值:
<0: 失败,设置errno
=0:非阻塞返回,并且没有收到尸体
>0: 收到的子进程的进程号
wait的代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
return -1;
}
else if (0 == pid) //child
{
sleep(1);
printf("child: pid = %d\n", getpid());
exit(10);
}
printf("parent!\n");
//pid = wait(NULL);
int wstatus;
pid = wait(&wstatus); //获取子进程退出状态
if (WIFEXITED(wstatus)) //判断是否是正常退出
{
printf("Child process exit normally!\n");
printf("exit: %d\n", WEXITSTATUS(wstatus)); //获取退出值
}
else
printf("Chils process exit unnormally!\n");
printf("wait: pid = %d\n", pid);
return 0;
}
waitpid代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
return -1;
}
else if (0 == pid) //child
{
sleep(1);
printf("child: pid = %d\n", getpid());
exit(0);
}
printf("parent!\n");
sleep(2);
// pid = waitpid(-1, NULL, 0); //阻塞等待任意子进程退出,获取子进程退出状态
pid = waitpid(-1, NULL, WNOHANG); //非阻塞等待任意子进程退出,获取子进程退出状态
if (0 > pid)
{
perror("waitpid");
return -1;
}
else if (0 == pid)
printf("No such child process exit!\n");
else
printf("wait: pid = %d\n", pid);
return 0;
}