Linux进程间通信IPC学习笔记之有名管道

基础知识:

有名管道,FIFO先进先出,它是一个单向(半双工)的数据流,不同于管道的是:是最初的Unix IPC形式,可追溯到1973年的Unix第3版。使用其应注意两点:

1)有一个与路径名关联的名字;

2)允许无亲缘关系的进程通信;

3)读写操作用read和write函数;

4)有open打开有名管道时,必须只能是只读或只写

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
参数:pathname是一个普通的Unix路径名,为FIFO的名字;mode用于给一个FIFO指定权限位
返回:若成功返回0,否则返回-1

#include <unistd.h>
ssize_t read(int fildes, void *buf, size_t nbyte); 
ssize_t write(int fildes, const void *buf, size_t nbyte); 
含义:以上同个函数用来存取有名管道中的数据
#include <fcntl.h>
int open(const char *path, int oflag, ... );
 含义:如果已存在一个有名管道,可以用它打开
#include <unistd.h>
int close(int fildes); 
 含义:关闭有名管道
#include <unistd.h>
int unlink(const char *path);
 含义:移除有名管道

测试代码:

 1 #include "stdio.h"
 2 #include "stdlib.h"
 3 #include "unistd.h"
 4 #include "sys/types.h"
 5 #include "sys/stat.h"
 6 #include "fcntl.h"
 7 #include "string.h"
 8 #define MAXLINE 256
 9 int  main(void)  
10 {
11     int rfd, wfd;
12     pid_t pid;
13     char line[MAXLINE];
14 
15     if (mkfifo("./fifo1", 0666) < 0)  
16         {
17                 printf("mkfifo error");
18         }
19 
20     if ((pid = fork()) < 0) 
21         {  
22                 printf("fork error"); 
23     } 
24         else if (pid > 0) 
25         {       
26         /* parent */
27         if((wfd = open("./fifo1", O_WRONLY)) > 0 )
28                 { 
29                         write(wfd, "hello\n", 13);
30                         close(wfd);
31                 } 
32         }
33         else 
34         {                /* child */
35         if((rfd = open("./fifo1", O_RDONLY)) > 0 )
36                 { 
37                         int n = read(rfd, line, MAXLINE);
38                         printf("%s", line);
39                         close(rfd);
40                 }
41         }
42 }

 

参考资料:

Linux进程线程学习笔记:进程间通信之管道

转载于:https://www.cnblogs.com/gjianw217/p/3290247.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值