为什么说极简呢,因为下面这个程序只能从一端写另一端读。(单工通信)
注意:有名管道用于系统中任意两个进程间通信(不需要有亲缘关系)
fifo_read.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int ret, fd;
char buf[100] = {0};
ret = mkfifo("fifo.tmp", O_CREAT | O_EXCL); //创建有名管道
if (-1 == ret) //创建失败
{
perror("fifo");
exit(1);
}
fd = open("fifo.tmp", O_RDONLY); //以只读方式打开
if(-1 == fd) //打开失败
{
perror("read");
exit(1);
}
while(1)
{
ret = read(fd, buf, sizeof(buf)); //读出缓冲区中的内容
if(ret == -1)
{
perror("read");
exit(1);
}
if(!strncmp(buf, "bye", 3)) //以bye结束
{
break; //跳出循环
}
printf("read from fifo.tmp: %s\n",buf);
memset(buf, 0, sizeof(buf)); //清空缓冲区
unlink("fifo.tmp"); //关掉管道文件,方便程序下次运行
}
return 0;
}
fifo_write.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char buf[100] = {0};
int fd, ret;
fd = open("fifo.tmp", O_WRONLY); //以只写方式打开
if(-1 == fd)
{
perror("open");
exit(1);
}
while(1)
{
scanf("%s",buf);
ret = write(fd, buf, strlen(buf)); //往缓冲区里面写
if(-1 == ret)
{
perror("write");
exit(1);
}
if(!strncmp(buf, "bye", 3)) //以bye结束
{
break;
}
memset(buf, 0, sizeof(buf)); //清空缓冲区
}
return 0;
}
上面两个程序(进程)前者为读,后者为写,注意第一个程序里面首先要创建一个有名管道,所以两个程序运行的先后顺序是前者先运行(此时,一直读到空)。运行结果如下: