一、AB进程对话
1.1 要求:
- A进程先发送一句话给B进程,B进程接收后打印
- B进程再回复一句话给A进程,A进程接收后打印
- 重复1.2步骤,当收到quit后,要结束AB进程
- 提示:两根管道
1.2 思路
- 需要俩有名管道
- 一个进程先对有名管道进行写入,然后等待读取另一个有名管道
- 而另一个相反,先等待读取有名管道数据,然后再进行写入
二、 代码实现
2.1 a_fifo.c
#include <my_head.h>
int main(int argc, const char *argv[])
{
umask(0);
if (mkfifo("fifo_a", 0664) < 0)
{
if (errno != EEXIST)
{
ERR_MSG("mkfifo");
return -1;
}
}
if (mkfifo("fifo_b", 0664) < 0)
{
if (errno != EEXIST)
{
ERR_MSG("mkfifo");
return -1;
}
}
int fd_w = open("fifo_a", O_WRONLY);
int fd_r = open("fifo_b", O_RDONLY);
char buff[128];
ssize_t res;
while (1)
{
bzero(buff, sizeof(buff));
printf("我说: ");
fgets(buff, sizeof(buff), stdin);
buff[strlen(buff) - 1] = 0;
if (0 == strcmp(buff, "exit"))
{
break;
}
if (write(fd_w, buff, sizeof(buff)) < 0)
{
ERR_MSG("write_a");
return -1;
}
printf("-----------------\n");
bzero(buff, sizeof(buff));
res = read(fd_r, buff, sizeof(buff));
if (res < 0)
{
ERR_MSG("read");
return -1;
}
else if (0 == res)
{
printf("对话结束\n");
break;
}
printf("B说: %s\n", buff);
}
return 0;
}
2.2 b_fifo.c
#include <my_head.h>
int main(int argc, const char *argv[])
{
umask(0);
if (mkfifo("fifo_a", 0664) < 0)
{
if (errno != EEXIST)
{
ERR_MSG("mkfifo");
return -1;
}
}
if (mkfifo("fifo_b", 0664) < 0)
{
if (errno != EEXIST)
{
ERR_MSG("mkfifo");
return -1;
}
}
int fd_r = open("fifo_a", O_RDONLY);
if (fd_r < 0)
{
ERR_MSG("open fd_r");
return -1;
}
int fd_w = open("fifo_b", O_WRONLY);
if (fd_w < 0)
{
ERR_MSG("open fd_r");
return -1;
}
char buff[128];
ssize_t res;
while (1)
{
bzero(buff, sizeof(buff));
res = read(fd_r, buff, sizeof(buff));
if (res < 0)
{
ERR_MSG("read");
return -1;
}
else if (0 == res)
{
printf("对话结束\n");
break;
}
printf("A说: %s\n", buff);
bzero(buff, sizeof(buff));
printf("我说: ");
fgets(buff, sizeof(buff), stdin);
buff[strlen(buff) - 1] = 0;
if (0 == strcmp(buff, "exit"))
{
break;
}
if (write(fd_w, buff, sizeof(buff)) < 0)
{
ERR_MSG("write_a");
return -1;
}
printf("-----------------\n");
}
return 0;
}