wait()函数:调用该函数使进程阻塞,直到任一个子进程结束或者是该进程接收到了一个信号为止。如果该进程没有子进程或者其子进程已经结束,wait函数会立即返回。
头文件
#include <sys/types.h>
#include <sys/wait.h>
函数原型
pid_t wait(int *status)
函数参数
status是一个整型指针,指向的对象用来保存子进程推出时的状态。
(1)status若为NULL,表示忽略子进程退出时的状态。
(2)status若不为NULL,表示保存子进程推出时的状态。
函数返回值
成功:子进程的进程号
失败:-1
代码段
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork error!\n");
return -1;
}
else if(pid > 0)
{
//父进程
wait(NULL);//
while(1)
{
printf("I am parent\n");
sleep(1);
}
}
else
{
//子进程
int i = 0;
while (1)
{
if (i > 3)
{
exit(1);
}
printf("I am child\n");
sleep(1);
i++;
}
}
return 0;
}
运行结果
waitpid()函数
waitpid () 函数被用来关注子进程的状态是否发生变化。 这些状态的变化包括 子进程终止 、 子进程被一个信号停止 、 子进程被一个信号恢复 。 如果子进程的状态变化为子进程退出,那么 waitpid () 函数可以对子进程的资源进行回收,让子进程的资源得以释放。
头文件
#include <sys/types.h>
#include <sys/wait.h>
函数原型
pid_t wait(pid_t pid ,int *status , int options)
函数参数
pid>0:只等待进程ID等于pid的子进程,不管已经有其他子进程运行结束退出,只要指定的子进程还没有结束,waitpid就一直会等下去。
pid=-1:等待任何一个子进程退出,此时和wait作用一样。
pid=0:等待其组ID等于调用进程的组ID的任一子进程。
pid<-1:等待其组ID等于pid的绝对值的任一子进程。
status是一个整型指针,指向的对象用来保存子进程推出时的状态。
(1)status若为NULL,表示忽略子进程退出时的状态。
(2)status若不为NULL,表示保存子进程推出时的状态。
函数返回值
正常:结束的子进程的进程号
使用选项WNOHANG且没有子进程结束时:0
调用出错:-1
代码段
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if (pid < 0)
{
perror("fork error!\n");
return -1;
}
else if(pid > 0)
{
//父进程
//wait(NULL);//阻塞父进程,等待子进程退出。
//waitpid(-1,NULL,0);//同wait(),阻塞父进程,等待子进程退出。
while(1)
{
int status = 0;
int ret = waitpid(-1,NULL,WNOHANG);//非阻塞
printf("ret = %d\n",ret);
printf("I am parent\n");
sleep(1);
}
}
else
{
//子进程
int i = 0;
while (1)
{
if (i > 3)
{
exit(1);
}
printf("I am child\n");
sleep(1);
i++;
}
}
return 0;
}
运行结果