IPC(1)-管道

1 概括介绍

     管道分为无名管道和有名管道。

2 无名管道

     是 UNIX 系统IPC最古老的形式。有如下的特点:

    1:半双工的,数据只能在一个方向上传输,有固定的读端和写端。

    2:只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。

    3:可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write 等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。

3 实例

3.1 涉及函数

#include <unistd.h>
int pipe(int fd[2]);/*返回值:若成功返回0,失败返回-1*/

当一个管道建立时,会创建两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。要关闭管道只需将这两个文件描述符关闭即可。

3.2 实例

如果从父进程发送数据到子进程,则关闭父进程的读端(fd[0])与子进程的写端(fd[1]);反之,则可从子进程发送数据到父进程。

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <string.h>
 4   
 5 int main()
 6 {
 7      int fd[2];  /*两个文件描述符*/
 8      pid_t pid;
 9      char buf_f[20];
10      char buf_b[20];
11      memset(buf_f,0,sizeof(buf_f));
12      memset(buf_b,0,sizeof(buf_b));
13      if(pipe(fd) < 0)  /*创建管道*/
14      {
15          printf("Create Pipe Error!\n");
16      }
17      if((pid = fork()) < 0)  /*创建子进程*/
18      {
19        printf("fork Error!\n");
20      }
21      else if(pid > 0)  /*父进程*/
22      {
23        close(fd[0]); /*关闭读端*/
24        buf_f = "hello boy,I'm father!!!";
25        write(fd[1], buf_f, 12);
26      }
27      else
28      {
29        close(fd[1]); /*关闭写端*/
30        read(fd[0], buf_b, 20);
31        printf("%s \n", buf_b);
32      }
33      return 0;
34 }
4 有名管道
主要用于非父子的进程间通信。
实例:
4.1 写端:
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 int main()
 6 {
 7   int fd = open("pipe_file",O_WRONLY);
 8 
 9   printf("fd = %d\n",fd);
10 
11   char buf[64] = {0};
12   while(1)
13   {
14     printf("plase input:\n");
15     fgets(buf,64,stdin);
16     write(fd,buf,strlen(buf));
17 
18     if(strncmp(buf,"end",3)==0)
19     {
20       break;
21     }
22   }
23   close(fd);
24   return 0;
25 }

4.2  读端

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 int main()
 6 {
 7   int fd = 0;
 8 
 9   int sum = 0;
10 
11   char buf[64] = {0};
12 
13   fd = open("pipe_file",O_RDONLY);
14   printf("fd = %d\n",fd);
15 
16   do
17   {
18 
19     sum = read(fd,buff,64))
20 
21     memset(buf,0,64);
22     printf("read:(n = %d)%s\n",n,buff);
23   }while(sum);
24 
25   close(fd);
26   return 0;
27 }
posted @ 2019-11-27 22:41  Action_er  阅读(290)  评论(0编辑  收藏  举报