要求实现父子进程对话

作业需求:

要求实现父子进程对话

1.父进程先发送一句话给子进程,子进程接收后打印

2.子进程再回复一句话给父进程,父进程接收后打印3.重复1.2步骤,

当收到quit后,要结束父子进程 

实现过程:

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

int main(int argc, const char *argv[])
{
	int pfd[2]={0};
	int pfd1[2]={0};
	char str[20]="";
	char str1[20]="";
    char str2[20]="quit";
	int i=0;
	pid_t ws;
	ssize_t res,res1;
	if(pipe(pfd)<0)
	{
		perror("pipe");
		return -1;
	}
	if(pipe(pfd1)<0)
	{
		perror("pipe2");
		return -1;
	}



	pid_t pid=fork();
	if(pid>0)
	{
		while(1)
		{
			fgets(str,sizeof(str),stdin);
			str[strlen(str)-1]='\0';
			if(strcmp(str,str2)==0)
				break;
			write(pfd[1],str,sizeof(str));
			bzero(str,sizeof(str));
			read(pfd1[0],str,sizeof(str));	
			printf("this is other %s\n",str);
		}

	}
	if(pid==0)
	{
		while(1)
		{
			bzero(str,sizeof(str));
			read(pfd[0],str,sizeof(str));
			printf("this is main %s\n",str);
			fgets(str,sizeof(str),stdin);
			str[strlen(str)-1]='\0';
			if(strcmp(str,str2)==0)
				break;
			write(pfd1[1],str,sizeof(str));

		}


	}	


	return 0;
}

实现结果:

ubuntu@ubuntu:07_day$ gcc ptf.c -pthread
ubuntu@ubuntu:07_day$ ./a.out
1
this is main 1
2
this is other 2
3
this is main 3
4
this is other 4
5
this is main 5
6
this is other 6
7
this is main 7
8
this is other 8
quit
ubuntu@ubuntu:07_day$ 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值