01多进程的创建

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

//#include<fcntl.h>
//1.实现多任务
void test01()
{
	pid_t pid=fork();
	if(0>pid)
	{
	 perror("fork error");		
	}
	else if(0==pid)//子进程返回0
	{
		printf("子进程返回的pid:%d\n",pid);//输出0
		printf("子进程的id:%d\n",getpid());
		while(1)
		{
			printf("这是一个子进程\n");
            sleep(1);			
		}	
	}
	else//父进程中返回子进程的ID
	{
		
		printf("子进程返回的pid:%d\n",pid);//输出子进程的id
		while(1)
		{
		printf("这是一个父进程\n");
           sleep(1);				
		}	
	}
	
}
//2.父、子进程的执行顺序由cpu决定,资源不共享
void test02()
{
	int num=10;
	
	pid_t pid2=fork();
	if(0>pid2)
	{
	 perror("fork error");		
	}
	else if(0==pid2)//子进程返回0
	{
		
		while(1)
		{
			printf("num1=%d",num);
			printf("这是一个子进程\n");
            sleep(1);			
		}	
	}
	else//父进程中返回子进程的ID
	{
		while(1)
		{
			num++;
			printf("num2=%d",num);
		printf("这是一个父进程\n");
         sleep(1);				
		}	
	}
	
}
//3.当正常执行程序./a.out,行缓冲就是行缓冲,如果将程序重定向,行缓冲变成全缓冲。
void test03()
{
	write(1,"hahahhahh",strlen("hahahhahh"));
	printf("行缓冲\n");
	printf("全缓冲");
	pid_t pid3=fork();
	if(pid3<0)
	{
		perror("fork error");
	}
	else if(0==pid3)
	{
		fflush(NULL);
		
	}
	else
	{
		fflush(NULL);
		
	}
	while(1);
	
		
}

//4.多进程的创建方式1,产生2的n次方个进程,进程愈多,进程的判定越麻烦,
//
void test04()
{
	pid_t pid_1=fork();
	pid_t pid_2=fork();
	if(pid_1==0&&pid_2>0)
	{
		printf("子进程1\n");
        printf("子进程1PID:%d PPID:%d\n",getpid(),getppid());		
	}
	else if(pid_1>0&&pid_2==0)
	{
		printf("子进程2\n");
         printf("子进程2PID:%d PPID:%d\n",getpid(),getppid());		
	}
	else if(pid_1==0&&pid_2==0)
	{
		printf("孙子进程\n");
         printf("孙子进程PID:%d PPID:%d\n",getpid(),getppid());			
	}
	else
	{
	  printf("父进程\n");
	  printf("父进程PID:%d\n",getpid());	
		
	}
	while(1);
	
	
}
//4.1 多进程的创建方式2 进程等待wait
void test05()
{
	
   int sta;
	int i=0;
	for(i=0;i<3;i++)
	{
		pid_t pid_3=fork();
		if(pid_3==0)
		{
		  break;		
		}			
	}
	if(i==0)
		printf("子进程1  %d---%d\n",getpid(),getppid());
	else if(i==1)
		printf("子进程2  %d-----%d\n",getpid(),getppid());
	else if(i==2)
		printf("子进程3  %d------%d\n",getpid(),getppid());
	else if(i==3)
	{
		printf("父进程   %d\n",getpid());
		//pid_t pid_3=wait(&sta);        /*一次只等待一个*/
		//pid_t  pid_3=waitpid(-1,&sta,0); /* 阻塞等待任意进程结束,也只等一个*/
		printf("回收的子进程的id:%d\n",pid_3);
	}		
		
}
int main()
{
	test05();
	return 0;
	
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值