1.waitpid能否回收兄弟进程
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t cpid = fork(); //子进程1
if(cpid > 0) //在父进程中为真,在子进程中为假
{
printf("father\n");
int ex_cpid = 0;
if(fork()==0) //子进程2
{
printf("child2\n");
waitpid(cpid,NULL,0);
printf("child2 is exited\n");
return 0;
}
ex_cpid = waitpid(-1,NULL,WNOHANG);//非阻塞方式回收子进程的资源
printf("ex_cpid = %d \n",ex_cpid);//返回0,运行的时候,子进程没有退出
while(1)
{
printf("father : %d child : %d %d\n",getpid(),cpid,__LINE__);
ex_cpid = waitpid(-1,NULL,WNOHANG);//非阻塞方式回收子进程的资源
printf("ex_cpid = %d \n",ex_cpid); //返回0,运行的时候,子进程没有退出
sleep(1);
}
}
else if(0 == cpid)
{
printf("this is child\n");//在子进程中为真,在父进程中为假
int i=0;
while(i < 2)
{
printf("--------------\n");
sleep(1);
i++;
}
printf("child process is ready to exit\n");
exit(20);
printf("child process is exit\n");
}
else if(cpid < 0)
{
perror("fork");
return -1;
}
return 0;
}
结果:
2.子能否收父
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t cpid = fork(); //子进程1
if(cpid > 0) //在父进程中为真,在子进程中为假
{
printf("father\n");
while(1)
{
printf("father : %d child : %d %d\n",getpid(),cpid,__LINE__);
sleep(1);
}
}
else if(0 == cpid)
{
printf("this is child\n");//在子进程中为真,在父进程中为假
int ex_cpid = 0;
ex_cpid = waitpid(getpid(),NULL,0); //阻塞方式回收父进程的资源
printf("ex_cpid = %d\n",ex_cpid);
int i=0;
while(i < 2)
{
printf("--------------\n");
sleep(1);
i++;
}
printf("child process is ready to exit\n");
exit(20);
printf("child process is exit\n");
}
else if(cpid < 0)
{
perror("fork");
return -1;
}
return 0;
}
结果: