1. 思路
2. 代码实现
talkA.c
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
#define SIZE 128
/*talkA进程*/
int main(int argc, const char* argv[]) {
int fdr = -1;
int fdw = -1;
int ret = -1;
char buf[SIZE];
// 1. 只读方式打开管道fifo_1,只写方式打开管道fifo_2
fdr = open("fifo_1", O_RDONLY);
if (-1 == fdr) {
perror("open");
return 1;
}
fdw = open("fifo_2", O_WRONLY);
if (-1 == fdw) {
perror("open");
return 1;
}
// 2. 循环读写
while (1) {
memset(buf, 0, SIZE);
ret = read(fdr, buf, SIZE); // 读管道
if (ret <= 0) {
perror("read");
break;
}
printf("talkB: %s\n", buf);
memset(buf, 0, SIZE);
printf("我: ");
fgets(buf, SIZE, stdin);
if ('\n' == buf[strlen(buf) - 1]) { // 将末尾换行符去掉
buf[strlen(buf) - 1] = '\0';
}
ret = write(fdw, buf, strlen(buf)); // 写管道
if (ret <= 0) {
perror("write");
break;
}
}
// 3. 关闭文件描述符
close(fdr);
close(fdw);
return 0;
}
talkB.c
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
#define SIZE 128
/*talkA进程*/
int main(int argc, const char* argv[]) {
int fdr = -1;
int fdw = -1;
int ret = -1;
char buf[SIZE];
// 1. 只写方式打开管道fifo_1,只读方式打开管道fifo_2
fdw = open("fifo_1", O_WRONLY);
if (-1 == fdw) {
perror("open");
return 1;
}
fdr = open("fifo_2", O_RDONLY);
if (-1 == fdr) {
perror("open");
return 1;
}
// 2. 循环写读
while (1) {
printf("我: ");
memset(buf, 0, SIZE);
fgets(buf, SIZE, stdin);
if ('\n' == buf[strlen(buf) - 1]) { // 将末尾换行符去掉
buf[strlen(buf) - 1] = '\0';
}
ret = write(fdw, buf, strlen(buf)); // 写管道
if (ret <= 0) {
perror("write");
break;
}
memset(buf, 0, SIZE);
ret = read(fdr, buf, SIZE); // 读管道
if (ret <= 0) {
perror("read");
break;
}
printf("talkA: %s\n", buf);
}
// 3. 关闭文件描述符
close(fdr);
close(fdw);
return 0;
}
测试结果: