pipe创建的管道只能在具有共同祖先的进程间通信,而mkfifo能在不相关的进程间交换数据。举例来说,匿名管道只能在一个项目文件中通信,类似消息队列;有名管道可在多个程序间通信,类似socket方式。
写端wfifo.c:
#include <stdio.h> #include <fcntl.h> #include <error.h> #include <stdlib.h> #include <string.h> #define SIZE 128 int main() { char buffer[SIZE]; int write_fd; int ret; int len; write_fd=open("./swap",O_WRONLY);//打开管道(只写) do { if(write_fd<0) { perror("open error"); exit(1); } printf("input data\n"); fgets(buffer,SIZE,stdin); len=strlen(buffer); buffer[len-1]='\0'; ret=write(write_fd,buffer,SIZE); if(ret==-1) { perror("write error"); exit(1); } printf("send success\n"); }while(strcmp(buffer,"exit")!=0); close(write_fd); return 0; }
读端 rfifo.c
#include <stdio.h> #include <fcntl.h> #include <error.h> #include <stdlib.h> #define SIZE 128 int main() { char buffer[SIZE]; int read_fd; int ret; read_fd=open("./swap",O_RDONLY); do { if(read_fd<0) { perror("open error"); exit(1); } ret=read(read_fd,buffer,SIZE); if(ret==-1) { perror("read error"); exit(1); } printf("the data is:\n"); printf("%s\n",buffer); }while(strcmp(buffer,"exit")!=0); close(read_fd); return 0; }
运行效果: