fifo管道间无血缘关系读写操作,下面直接上代码。
read.c
#include
#include
#include
#include
#include
#include
#include
/*
* 进程 A -- 读操作 -- fifo
*/
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("./a.out fifoname\n");
exit(1);
}
// 判断文件是否存在
int ret = access(argv[1], F_OK);
if(ret == -1)
{
// 创建管道
int r = mkfifo(argv[1], 0664);
if(r == -1)
{
perror("mkfifo");
exit(1);
}
else
{
printf("有名管道创建成功!\n");
}
}
// 打开管道
int fd = open(argv[1], O_RDONLY);
if(fd == -1)
{
perror("open");
exit(1);
}
// 读管道
while(1)
{
char buf[1024];
read(fd, buf, sizeof(buf));
printf("buf = %s\n", buf);
}
close(fd);
return 0;
}
write.c
#include
#include
#include
#include
#include
#include
#include
/*
* 进程 B -- 写操作 -- fifo
*/
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("./a.out fifoname\n");
exit(1);
}
// 判断文件是否存在
int ret = access(argv[1], F_OK);
if(ret == -1)
{
// 创建管道
int r = mkfifo(argv[1], 0664);
if(r == -1)
{
perror("mkfifo");
exit(1);
}
else
{
printf("有名管道创建成功!\n");
}
}
//写操作
int fd = open(argv[1],O_WRONLY);
if(fd == -1)
{
perror("open");
exit(1);
}
//写管道
while(1)
{
char str[100];
scanf("%s",str);
//char *p = "hello word!";
write(fd,str,strlen(str)+1);
}
close(fd);
return 0;
}
代码写完,分别在两个终端进行编译执行这两个进程。
终端一:
//编译读文件
gcc read.c -o read
//执行读文件,带上abc这个管道
./read abc
终端二:
//编译写文件
gcc write.c -o write
//执行写文件,带上abc这个管道
./write abc
//在该终端输入字符串回车
...
...