1.若没有子进程 waitpid函数能否运行成功
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
int ex_cpid=0;
if(cpid>0)
{
printf("this is parent\n");
while(1)
{
printf("parent:%d child:%d %d\n",getpid(),cpid,__LINE__);
ex_cpid=waitpid(-1,NULL,WNOHANG);
printf("excpid=%d\n",ex_cpid);
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(1);
}
else if(cpid<0)
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
当没有子进程时,函数会运行失败。
2.waitpid能否回收兄弟进程
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();//子1
int ex_cpid=0;
if(cpid>0)
{
printf("this is parent\n");
if(fork()==0)//子2
{
printf("子2\n");
printf("ex_cpid=%d\n",waitpid(cpid,NULL,0));
printf("子2退出\n");
return 0;
}
while(1)
{
printf("parent:%d child:%d %d\n",getpid(),cpid,__LINE__);
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(1);
}
else if(cpid<0)
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
兄弟进程间无法相互回收
3. waitpid子进程能否回收父进程
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
pid_t cpid=fork();
int ex_cpid=0;
if(cpid>0)
{
printf("this is parent\n");
while(1)
{
printf("parent:%d child:%d %d\n",getpid(),cpid,__LINE__);
exit(0);
sleep(1);
}
}
else if(0==cpid)
{
printf("this is child\n");
ex_cpid=waitpid(getppid(),NULL,0);
printf("excpid=%d\n",ex_cpid);
int i=0;
while(i<2)
{
printf("------\n");
sleep(1);
i++;
}
printf("child process is ready to exit\n");
exit(1);
}
else if(cpid<0)
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
子进程无法回收父进程资源。