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进程线程学习笔记:进程间通信之管道

posted on 2013-08-29 20:18  鹰之翔  阅读(255)  评论(0编辑  收藏  举报

导航