Linux作业

2023-5-11作业

创建AB进程,要求如下:

A进程先发送一句话给B进程,B进程接收到后打印到终端上;

在a要求之后,B进程发送一句话给A进程,A进程接收后打印。

重复a, b步骤,直到发送或者接收到quit后,结束AB进程。

#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<pthread.h>

int main(int argc,const char *argv[])
{
	int pfd[2]={0};		//管道创建
	if(pipe(pfd)<0)		
	{
		perror("pipe");
		return -1;
	}
	char buf[128];
	pid_t cpid=fork();	//父进程创建
	if(0<cpid)
	{
		close(pfd[0]);
		while(1)
		{
			fgets(buf,sizeof(buf),stdin); 	//终端获取元素
			putchar(10);
			buf[strlen(buf)-1]=0;
			if(strcasecmp(buf,"quit")==0)
			{
				break;
			}

			if(write(pfd[1],buf,sizeof(buf))<0)	//写入管道文件中
			{
				perror("write");
				return -1;
			}
		}
	}
	else if(0==cpid)	//子进程创建
	{
		close(pfd[1]);
		ssize_t res=0;
		while(1)
		{
			bzero(buf,sizeof(buf));
			res=read(pfd[0],buf,sizeof(buf));	//子进程读取管道文件中内容
			if(res<0)
			{
				perror("read");
				return -1;
			}
			else if(0==res)
			{
				printf("write close pipe is not data\n");
				break;
			}
			printf("%s\n",buf);		//读取到的内容打印到终端
			putchar(10);
			if(strcasecmp(buf,"quit")==0)	//如果输入quit则退出
			{
				break;
			}
		}
	}	
	else
	{
		perror("fork");
		return -1;
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值