1.waitpid能否回收兄弟进程
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#define ERR_MSG(msg) {\
fprintf(stderr,"line: %d\n",__LINE__);\
perror(msg);\
}
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0){
//int type = 0;
//type = waitpid(-1,NULL,0);
//printf("%d %d\n",type,cpid);
pid_t cpid2 = fork();
if(cpid2 == 0){
int type = 0;
type = waitpid(-1,NULL,0);
printf("%d 子进程结束2\n",type);
}
while(1)
sleep(1);
}
else if(cpid == 0){
printf("子进程结束1\n");
}
return 0;
}
可以看到兄弟进程无法回收彼此
2.子能否收父
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#define ERR_MSG(msg) {\
fprintf(stderr,"line: %d\n",__LINE__);\
perror(msg);\
}
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0){
printf("父进程结束\n");
}
else if(cpid == 0){
int type = 0;
type = waitpid(-1,NULL,0);
printf("%d %d\n",type,cpid);
while(1)
sleep(1);
}
return 0;
}
可以看到子进程无法回收父进程
3.若没有子进程 waitpid函数能否运行成功
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#define ERR_MSG(msg) {\
fprintf(stderr,"line: %d\n",__LINE__);\
perror(msg);\
}
int main(int argc, const char *argv[])
{
int type = 0;
type = waitpid(-1,NULL,0);
printf("%d\n",type);
while(1)
sleep(1);
return 0;
}
可以看到若没有子进程,waitpid无法运行成功
总结:waitpid只能父进程回收子进程。