IO day5 :进程

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;
}

结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值