一般运用这两个函数,是在父进程等待子进程退出的过程中
区别:wait使调用者阻塞,waitpid有一个选项,可以使调用者不阻塞
status参数是一个整型数指针
非空:子进程退出状态放在它所指向的地址中。
空:不关心退出状态
那么父进程为啥要等待子进程退出?因为子进程退出状态不被收集,就会变成僵尸进程,Linux中用z+显示(英文单词zombie)
wait函数:使调用者阻塞,用来等待子进程退出(后面有附加代码验证)
编译结果:
waitpid函数:可以使调用者不阻塞,则父进程子进程一起运行(后面有附加代码验证)
编译结果:
附加代码验证(wait):
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
int status = 10;
pid = fork();
if(pid > 0)
{
wait(&status);
printf("child quit, child status = %d\n",WEXITSTATUS(status));
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 5){
exit(3);
}
}
}
return 0;
}
附加代码验证(waitpid):
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
int status = 10;
pid = fork();
if(pid > 0)
{
waitpid(pid,&status,WNOHANG);
printf("child quit, child status = %d\n",WEXITSTATUS(status));
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print, pid = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0){
while(1){
printf("this is chilid print, pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 5){
exit(3);
}
}
}
return 0;
}