Chinaunix首页 | 论坛 | 博客
  • 博客访问: 389072
  • 博文数量: 75
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2015-06-03 18:24
文章分类

全部博文(75)

文章存档

2019年(1)

2018年(20)

2017年(14)

2016年(10)

2015年(30)

分类: 嵌入式

2015-06-26 22:11:43

现在linux的进程间的通信方式有下面几种:管道(pipe)、有名管道(fifo)、信号、消息队列、共享内存、信号量、套接字等。

 

下面主要就介绍管道:

1、 管道的特点:

①半双工的通信方式

②只能在只有亲缘关系进程间进行通信

2、 相关函数介绍

函数说明:pipe()会建立管道,并将文件描述词由参数pipefd数组返回。

Pipefd[0]为管道里的读端,pipefd[1]为管道里的写端。

返回值:  若成功则返回零,否则返回-1,错误原因存于errno中。

 

3、 下面我们来测试下管道的大小

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<unistd.h>
  3. #include<stdlib.h>

  4. int main(void)
  5. {
  6.     int fd[2];
  7.     int count = 0;
  8.     if( pipe(fd) < 0 )
  9.     {
  10.         perror("fail to create pipe");
  11.         exit(1);
  12.     }

  13.     while(1)
  14.     {
  15.         write(fd[1],"a",sizeof(char));
  16.         printf("count = %d\n",++count);
  17.     }

  18.     return 0;
  19. }

上面这段代码就是不断给管道的写端写数据,直到缓冲区满了以后就会阻塞。通过测试我们可以发现管道的大小为65536个字节。

 

4、 管道的一些细节特点的

①只有管道的读端存在时,才能向管道写入数据。否则向管道写入数据,进程会收到内核传来的SIGPIPE信号(该信号的默认动作是程序终止)。

 

下面通过例子来说明这一点。

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<unistd.h>
  3. #include<stdlib.h>
  4. #include<signal.h>

  5. void handler(int signum)/*信号处理函数*/
  6. {
  7.     printf("rev SIGPIPE\n");
  8. }

  9. int main(void)
  10. {
  11.     int fd[2];
  12.     int count = 0;

  13.     signal(SIGPIPE,handler);
  14.     
  15.     if( pipe(fd) < 0 )
  16.     {
  17.         perror("fail to create pipe");
  18.         exit(1);
  19.     }

  20.     close(fd[0]);
  21.     write(fd[1],"a",sizeof(char));

  22.     return 0;
  23. }

编译执行后:

 

 

5、 父子进程间的通信

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<unistd.h>

  4. int main(void)
  5. {
  6.     int fd[2];
  7.     int pid;
  8.     if( pipe(fd) < 0 )
  9.     {
  10.         perror("fail to pipe");
  11.         exit(1);
  12.     }

  13.     if( (pid = fork()) < 0 )
  14.     {
  15.         perror("fail to fork");
  16.         exit(1);
  17.     }
  18.     else if(0 == pid) /*child*/
  19.     {
  20.         close(fd[1]);
  21.         int read_data;
  22.         char buf[10];
  23.         read_data = read(fd[0],buf,sizeof(buf));
  24.         printf("read_data=%d\n",read_data);
  25.         printf("buf:%s\n",buf);
  26.     }
  27.     else /*parent*/
  28.     {
  29.         close(fd[0]);
  30.         write(fd[1],"hello",sizeof("hello"));
  31.         close(fd[1]);
  32.     }

  33.     return 0;
  34. }

执行结果为:



写此文章就是为了巩固以前学的一些知识,也参考了些文章。http://blog.chinaunix.net/uid-26833883-id-3227144.html





阅读(1410) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~