写操作:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main()
{
char *str="message from fifo";
int fd=open("./file",O_WRONLY);
printf("write open success\n");
write(fd,str,strlen(str));
close(fd);
return 0;
}
运行效果:

读操作:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
char buf[30]={0};
if(mkfifo("./file",0600)==-1&&errno==EEXIST)
{
printf("mkfifo failauer\n");
perror("why");
}
int fd=open("./file",O_RDONLY);
printf("open success\n");
int n_read=read(fd,buf,30);
printf("read %d byte from fifo,context:%s\n",n_read,buf);
close(fd);
return 0;
}
运行效果:

O_WRONLY:以写的方式打开
O_RDONLY: 以读的方式打开
——@上官可编程
FIFO管道文件读写示例
本文提供了两个简单的C程序示例,演示了如何使用FIFO(命名管道)进行进程间通信。一个程序用于写入消息到FIFO,另一个程序则从FIFO中读取消息并打印出来。通过这两个示例,读者可以了解到FIFO的基本用法及其在进程间通信中的作用。
552

被折叠的 条评论
为什么被折叠?



