wait()函数
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int status;
int data = 0;
pid = fork();
if(pid == 0){
while(1){
printf("this is in child : data = %d\n",data);
data++;
sleep(1);
if(data == 3){
exit(5);
}
}
}else if(pid > 0){
wait(&status);
printf("status = %d\n",WEXITSTATUS(status));
while(1){
printf("this is in father : data = %d\n",data);
data++;
sleep(1);
}
}
return 0;
}
2.waitpid()函数
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int status;
int data = 0;
pid = fork();
if(pid == 0){
while(1){
printf("this is in child : data = %d pid = %d\n",data,getpid());
data++;
sleep(1);
if(data == 3){
exit(5);
}
}
}else if(pid > 0){
waitpid(pid, &status, WNOHANG);
printf("status = %d\n",WEXITSTATUS(status));
while(1){
printf("this is in father : data = %d pid = %d\n",data,getpid());
data++;
sleep(1);
}
}
return 0;
}
waitpid()函数的第三个参数可以设置阻塞或非阻塞。