linux读写fifo,fifo无血缘关系读写操作

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

//在该终端输入字符串回车

...

...

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值