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