A进程发送一句话后,B进程接,收到打印。然后B进程发送一句话,A进程接收后打印
重复上述步骤。直到AB接收或者发送完quit后,结束AB进程
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[])
{
if (mkfifo("./FIFO", 0664) < 0)
{
if (errno != 17)
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo1 success\n");
if (mkfifo("./FIFO2", 0664) < 0)
{
if (errno != 17)
{
perror("mkfifo");
return -1;
}
}
printf("mkfifo success\n");
pid_t cpid = fork();
if (cpid > 0)
{
int fd = open("./FIFO", O_RDWR);
if (fd < 0)
{
perror("open");
return -1;
}
printf("open success\n");
char buf[128] = "";
ssize_t res = 0;
while (1)
{
printf("请A输入消息>>>");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
if (write(fd, buf, strlen(buf) + 1) < 0)
{
perror("write");
return -1;
}
printf("A发送成功\n");
res = read(fd, buf, sizeof(buf));
if (res < 0)
{
perror("read");
return -1;
}
else if (res == 0)
{
printf("B写端关闭!");
break;
}
printf("A收到消息: %s\n", buf);
if (strcmp(buf, "quit") == 0)
break;
}
close(fd);
}
else if (cpid == 0)
{
int fd2 = open("./FIFO2", O_RDWR);
if (fd2 < 0)
{
perror("open");
return -1;
}
printf("open success\n");
char buf2[128] = "";
ssize_t res2 = 0;
while (1)
{
res2 = read(fd2, buf2, sizeof(buf2));
if (res2 < 0)
{
perror("read");
return -1;
}
else if (res2 == 0)
{
printf("A写端关闭!");
break;
}
printf("B收到消息: %s\n", buf2);
if (strcmp(buf2, "quit") == 0)
break;
printf("请B输入回复>>>");
fgets(buf2, sizeof(buf2), stdin);
buf2[strlen(buf2) - 1] = '\0';
if (write(fd2, buf2, strlen(buf2) + 1) < 0)
{
perror("write");
return -1;
}
printf("B发送成功\n");
}
close(fd2);
}
else
{
perror("fork");
return -1;
}
return 0;
}