实现AB进程对话。
A进程发送一句话后,B进程接收到打印。然后B进程发送一句话,A进程接收后打印
重复上述步骤。直到AB接收或者发送完quit后,结束AB进程
A进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建管道fifo1
if(mkfifo("./zuoye_fifo1", 0664) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
printf("fifo1创建成功!\n");
//创建管道fifo2
if(mkfifo("./zuoye_fifo2", 0664) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
printf("fifo2创建成功!\n");
//写
int fo = open("./zuoye_fifo1", O_WRONLY);
if(fo < 0)
{
perror("open");
return -1;
}
printf("open wronly success!!!\n");
//读
int fo2 = open("./zuoye_fifo2", O_RDONLY);
if(fo < 0)
{
perror("open");
return -1;
}
printf("open rdonly success!!!\n");
char buf[200] = "";
ssize_t res = 0;
while(1)
{
//写
printf("请输入数据:");
fgets(buf, sizeof(buf), stdin); //从终端获取数据
buf[strlen(buf)-1] = '\0';
if(write(fo, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
printf("写入成功\n");
if(strcmp(buf, "quit") == 0)
break;
//读
bzero(buf, sizeof(buf));
//读写端均存在,管道中没有数据,read函数阻塞
res = read(fo2, buf, sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(res == 0)
{
printf("写端关闭,且管道中没有数据\n");
break;
}
printf("%ld:%s \n", res, buf);
if(strcmp(buf, "quit") == 0)
break;
}
close(fo);
return 0;
}
B进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//创建管道fifo1
if(mkfifo("./zuoye_fifo1", 0664) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
printf("fifo1创建成功!\n");
//创建管道fifo2
if(mkfifo("./zuoye_fifo2", 0664) < 0)
{
if(errno != EEXIST)
{
perror("mkfifo");
return -1;
}
}
printf("fifo2创建成功!\n");
//读
int fo = open("./zuoye_fifo1", O_RDONLY);
if(fo < 0)
{
perror("open");
return -1;
}
printf("open rdonly success!!!\n");
//写
int fo2 = open("./zuoye_fifo2", O_WRONLY);
if(fo < 0)
{
perror("open");
return -1;
}
printf("open wronly success!!!\n");
char buf[200] = "";
ssize_t res = 0;
while(1)
{
//读
bzero(buf, sizeof(buf));
//读写端均存在,管道中没有数据,read函数阻塞
res = read(fo, buf, sizeof(buf));
if(res < 0)
{
perror("read");
return -1;
}
else if(res == 0)
{
printf("写端关闭,且管道中没有数据\n");
break;
}
printf("%ld:%s \n", res, buf);
if(strcmp(buf, "quit") == 0)
break;
//写
printf("请输入数据:");
fgets(buf, sizeof(buf), stdin); //从终端获取数据
buf[strlen(buf)-1] = '\0';
if(write(fo2, buf, sizeof(buf)) < 0)
{
perror("write");
return -1;
}
printf("写入成功\n");
if(strcmp(buf, "quit") == 0)
break;
}
close(fo);
return 0;
}