//管道文件写端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int ret = mkfifo("./myfifo",0666);
if(ret == -1)
{
perror("mkfifo failed:\n");
exit(0);
}
int fd = open("./myfifo",O_WRONLY);
if(fd == -1)
{
perror("open fifo failed:\n");
exit(0);
}
int i;
for(i = 0; i < 3;i++)
{
int ret1 = fork();
if(ret1 == -1)
{
perror("fork failed:\n");
exit(0);
}
if(ret1 == 0)
break;
else
continue;
}
if(i == 0)
{
char *a = "abc";
int ret2 = write(fd,a,strlen(a));
if(ret2 == -1)
{
perror("write a failed:\n");
exit(0);
}
close(fd);
}
if(i == 1)
{
char *b = "123";
int ret3 = write(fd,b,strlen(b));
if(ret3 == -1)
{
perror("write b failed:\n");
exit(0);
}
close(fd);
}
if(i == 2)
{
char *c = "hhh";
int ret4 = write(fd,c,strlen(c));
if(ret4 == -1)
{
perror("write c failed:\n");
exit(0);
}
close(fd);
}
else
{
for(i = 0;i < 3;i++)
wait(NULL);
close(fd);
}
return 0;
}
//管道文件读端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd = open("./myfifo",0666);
char get[50];
read(fd,get,50);
printf("read:%s\n",get);
return 0;
}
上述代码需要先运行写段代码再运行读端代码,因为写端代码才能穿创建管道文件,且假如有管道文件需要删除再原型代码。或者加入access()函数是否存在管道文件,不存在就创建管道文件。
注意点:
(1)管道文件不能使用函数lseek()定位
(2)最先写入管道的数据最先读取出来
(3)有名管道支持同时写入,具有写入原子性,linux的系统日志文件就是采用有名管道的写入原子性实现的,许多进程同时把运行状态消息写入管道,再从管道写到日志文件,这样子这些信息就不会因为同时写入而互相践踏
(4)关于open( )管道文件的阻塞问题:
在没有设置非阻塞的打开的情况下,不可以在只有写端或者读端的时候打开,会阻塞
在非阻塞模式可以先打开写端,写端会在read()阻塞,若先打开写端则会返回-1
(5)读写的阻塞和无名管道一样