#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
int main(){
int fd,sc;
char buf[1024];
//用只写打开fifo文件
if((fd = open("fifo",O_WRONLY)) < 0){
perror("Open fifo failed\n");
exit(1);
}
//循环写入内容
while(1){
printf("Write message: ");
gets(buf);
sc = write(fd,buf,strlen(buf)+1);
if(sc < 0){
perror("Write failed\n");
close(fd);
exit(1);
}
}
close(fd);
return 0;
}
创建进程对管道进行写 fifo_read.c,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
int main(){
int fd,rd;
char buf[1024];
//创建fifo管道
if((mkfifo("fifo",0664) < 0) && errno!=EEXIST){
perror("Create fifo failed\n"); exit(1);
}
//用只读打开fifo文件
if((fd = open("fifo",O_RDONLY)) < 0){
perror("Open fifo failed\n");
exit(1);
}
//实时读取fifo文件中的内容
while(1){
rd = read(fd,buf,1024);
if(rd < 0){
perror("Read error\n");
exit(1);
}
printf("Read message: %s\n", buf);
}
close(fd);
return 0;
}
编译成功后,打开两个服务器,在一个服务器上运行fifo_write.c文件,在另一个服务器上运行fifo_read.c文件,实时监控写入fifo文件的内容:

原文:https://www.cnblogs.com/jmuaia-wll/p/12723494.html