对父进程,子进程的waitpid操作

waitpid函数不能用于回收兄弟进程,只能由父进程用来等待并回收其子进程。当没有子进程时,waitpid函数将不会成功。文章通过三个示例代码展示了waitpid的功能限制:1)父进程不能通过waitpid回收兄弟进程;2)子进程无法回收父进程;3)没有子进程时,waitpid调用失败。
摘要由CSDN通过智能技术生成

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只能父进程回收子进程。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值