可以试试 命名管道
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
// 父进程负责从标准输入读取数据,然后写到fifo
// 子进程负责从fifo读取数据,然后写到标准输出
int main(int argc, char *argv[]) {
if(argc != 2) return -1;
int fd[2];
if(!strcmp(argv[1], "a")) {
fd[0] = open("fifo_0", O_RDONLY);
fd[1] = open("fifo_1", O_WRONLY);
} else if(!strcmp(argv[1], "b")) {
fd[1] = open("fifo_0", O_WRONLY);
fd[0] = open("fifo_1", O_RDONLY);
} else return -1;
if(!fork()) {
while(1) {
char buff[1024];
ssize_t nbyte = read(fd[0], buff, 1024);
write(1, buff, nbyte);
if(nbyte == 0 || !strncmp(buff, "exit", 4)) {
close(fd[0]); close(fd[1]); exit(0);
}
}
}
while(1) {
char buff[1024];
ssize_t nbyte = read(0, buff, 1024);
write(fd[1], buff, nbyte);
if(nbyte == 0 || !strncmp(buff, "exit", 4)) {
close(fd[0]); close(fd[1]); exit(0);
}
}
return 0;
}
|