一、AB进程对话
1.1 要求:
- A进程先发送一句话给B进程,B进程接收后打印
- B进程再回复一句话给A进程,A进程接收后打印
- 重复1.2步骤,当收到quit后,要结束AB进程
- 提示:两根管道
1.2 思路
- 需要俩有名管道
- 一个进程先对有名管道进行写入,然后等待读取另一个有名管道
- 而另一个相反,先等待读取有名管道数据,然后再进行写入
二、 代码实现
2.1 a_fifo.c
#include
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
2.2 b_fifo.c
#include
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76