Linux进程间通信(IPC)编程实践(一) 基本概念和匿名管道

       进程间通信至少可以通过传送打开文件来实现,不同的进程通过一个或多个文件来传递信息,事实上,在很多应用系统里,都使用了这种方法。但一般说来, 进程间通信(IPC:InterProcess Communication)不包括这种似乎比较低级的通信方法。Unix系统中实现进程间通信的方法很多,而且不幸的是,极少方法能在所有的Unix系 统中进行移植(唯一一种是半双工的管道,这也是最原始的一种通信方式)。而Linux作为一种新兴的操作系统,几乎支持所有的Unix下常用的进程间通信 方法:管道、消息队列、共享内存、信号量、套接口等等。


管道概念

   管道是Unix中最古老的进程间通信的形式,我们把从一个进程连接到另一个进程的一个数据流称为一个“管道”, 管道的本质是固定大小的内核缓冲区;它包括无名管道和有名管道两种,前者用于父进程和子进程间的通信,后者用于运行于同一台机器上的任意两个进程间的通信 

管道限制

   1)管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道;

   2)匿名管道只能用于具有共同祖先的进程(如父进程与fork出的子进程)之间进行通信, 原因是pipe创建的是两个文件描述符, 不同进程直接无法直接获得;(通常,一个管道由一个进程创建,然后该进程调用fork,此后父子进程共享该管道)

匿名管道创建

[cpp]  view plain  copy
  1. #include <unistd.h>    
  2. int pipe(int pipefd[2]);    

参数

   Pipefd:文件描述符数组,其中pipefd[0]表示读端,pipefd[1]表示写端,示意图如下:


(1)接下来,我们利用匿名管道来进行父子进程之间的通信,子进程向父进程发送信息。

[cpp]  view plain  copy
  1. int main()  
  2. {  
  3.         int pipefd[2];  
  4.         if(pipe(pipefd)==-1)  
  5.                 ERR_EXIT("pipe error!");  
  6.         pid_t pid;  
  7.         pid=fork();  
  8.         if(pid==-1)  
  9.                 ERR_EXIT("fork error");  
  10.         if(pid==0)  
  11.         {  
  12.                 close(pipefd[0]);  
  13.                 write(pipefd[1],"hello",5);  
  14.                 close(pipefd[1]);  
  15.                 exit(EXIT_SUCCESS);  
  16.         }  
  17.         close(pipefd[1]);  
  18.         char buf[10]={0};  
  19.         read(pipefd[0],buf,10);  
  20.         printf("buf=%s\n",buf);  
  21.    
  22.         return 0;  
  23.    
  24. }  
结果:父进程接收到子进程发送的hello

(2)我们来模拟实现管道命令 ls | wc -w   关键点就是:

   1.子进程运行ls,dup2pipefd[1],STDOUT_FILENO)重定向标准输出,定位到管道写端,ls写入到管道写端而不是标准输出设备;

   2.父进程运行wc -w ,wc获取数据的时候从管道读端获取,不再从标准输入设备。

   3.通过管道将子进程的输出发送到wc的输入 。

[cpp]  view plain  copy
  1. int main()  
  2. {  
  3.         int pipefd[2];  
  4.         if(pipe(pipefd)==-1)  
  5.                 ERR_EXIT("pipe error!");  
  6.         pid_t pid;  
  7.         pid=fork();  
  8.         if(pid==-1)  
  9.                 ERR_EXIT("fork error");  
  10.         if(pid==0)  
  11.         {  
  12.                 dup2(pipefd[1],STDOUT_FILENO);//重定向输出  
  13.                 close(pipefd[0]);  
  14.                 close(pipefd[1]);  
  15.                 execlp("ls","ls",NULL);//若出错才执行下面的代码  
  16.                 fprintf(stderr,"error execute ls\n");  
  17.                 exit(EXIT_FAILURE);  
  18.                    
  19.         }  
  20.         dup2(pipefd[0],STDIN_FILENO);  
  21.         close(pipefd[0]);  
  22.         close(pipefd[1]);  
  23.         execlp("wc","wc","-w",NULL);  
  24.         fprintf(stderr,"error execute wc\n");  
  25.         exit(EXIT_FAILURE);  
  26.         return 0;  
  27.    
  28. }  

(3)实现cp操作

不带任何参数的cat命令是从标准输入读入命令,写到标准输出。0->Makefile   ;    1->Makefile2;

[cpp]  view plain  copy
  1. int main()  
  2. {  
  3.         close(0);  
  4.         open("Makefile",O_RDONLY);  
  5.         close(1);  
  6.         open("Makefile2",O_WRONLY | O_CREAT | O_TRUNC,0644);  
  7.         execlp("cat","cat",NULL);  
  8.    
  9.         return 0;  
  10.    
  11. }  
管道的读写规则



我们对以上的规则一一进行验证。

(1)如果管道为空,那么read会阻塞(模式),如果使用非阻塞模式的话,也就是使用fcntl函数,对模式进行修改后

[cpp]  view plain  copy
  1. int flags=fcntl(pipefd[0],F_SETFL,flags | O_NONBLOCK);  
  2. read(pipefd[0],buf,10);  

此时,读操作会失败,显示资源暂且不可用的错误。

(2)管道的写端关闭,read打印输出0,但是并不报错误,显示读到了文件的末尾。

[cpp]  view plain  copy
  1. int main()    
  2. {    
  3.     int pipefd[2];    
  4.     if (pipe(pipefd) != 0)    
  5.         err_exit("pipe error");    
  6.     
  7.     pid_t pid = fork();    
  8.     if (pid == -1)    
  9.         err_exit("fork error");    
  10.     else if (pid == 0)    
  11.     {    
  12.         close(pipefd[1]);    
  13.         exit(EXIT_SUCCESS);    
  14.     }    
  15.     
  16.     close(pipefd[1]);    
  17.     sleep(2);    
  18.     char buf[2];    
  19.     if (read(pipefd[0], buf, sizeof(buf)) == 0)    
  20.         cout << "sure" << endl;    
  21. }    
(3) 如果所有管道读端对应的文件描述符被关闭,则write操作会产生信号SIGPIPE,进程终止。如果我们自定义SIGPIPE的处理函数的话会生效。

[cpp]  view plain  copy
  1. int main()    
  2. {    
  3.     if (signal(SIGPIPE, handler) == SIG_ERR)    
  4.         err_exit("signal error");    
  5.     
  6.     int pipefd[2];    
  7.     if (pipe(pipefd) != 0)    
  8.         err_exit("pipe error");    
  9.     
  10.     pid_t pid = fork();    
  11.     if (pid == -1)    
  12.         err_exit("fork error");    
  13.     else if (pid == 0)    
  14.     {    
  15.         close(pipefd[0]);    
  16.         exit(EXIT_SUCCESS);    
  17.     }    
  18.     
  19.     close(pipefd[0]);    
  20.     sleep(2);    
  21.     char test;    
  22.     if (write(pipefd[1], &test, sizeof(test)) < 0)    
  23.         err_exit("write error");    
  24. }    
会打印出  singal error错误。

(4)关于PIPE_BUF和原子性操作之间的关系,

   已知管道的PIPE_BUF4K, 我们启动两个进程A, B向管道中各自写入68K的内容然后我们以4K为一组, 为了方便我们查看管道最后一个字节的内容多运行该程序几次就会发现这68K的数据会有交叉写入的情况 。

[cpp]  view plain  copy
  1. int main()    
  2. {    
  3.     const int TEST_BUF = 68 * 1024; //设置写入的数据量为68K    
  4.     char bufA[TEST_BUF];    
  5.     char bufB[TEST_BUF];    
  6.     memset(bufA, 'A'sizeof(bufA));    
  7.     memset(bufB, 'B'sizeof(bufB));    
  8.     
  9.     int pipefd[2];    
  10.     if (pipe(pipefd) != 0)    
  11.         err_exit("pipe error");    
  12.     
  13.     pid_t pid;    
  14.     if ((pid = fork()) == -1)    
  15.         err_exit("first fork error");    
  16.     else if (pid == 0)  //第一个子进程A, 向管道写入bufA    
  17.     {    
  18.         close(pipefd[0]);    
  19.         int writeBytes = write(pipefd[1], bufA, sizeof(bufA));    
  20.         cout << "A Process " << getpid() << ", write "    
  21.              << writeBytes << " bytes to pipe" << endl;    
  22.         exit(EXIT_SUCCESS);    
  23.     }    
  24.     
  25.     if ((pid = fork()) == -1)    
  26.         err_exit("second fork error");    
  27.     else if (pid == 0)  //第二个子进程B, 向管道写入bufB    
  28.     {    
  29.         close(pipefd[0]);    
  30.         int writeBytes = write(pipefd[1], bufB, sizeof(bufB));    
  31.         cout << "B Process " << getpid() << ", write "    
  32.              << writeBytes << " bytes to pipe" << endl;    
  33.         exit(EXIT_SUCCESS);    
  34.     }    
  35.     
  36.     // 父进程    
  37.     close(pipefd[1]);    
  38.     sleep(2);   //等待两个子进程写完    
  39.     char buf[4 * 1024]; //申请一个4K的buf    
  40.     int fd = open("save.txt", O_WRONLY|O_TRUNC|O_CREAT, 0666);    
  41.     if (fd == -1)    
  42.         err_exit("file open error");    
  43.     
  44.     while (true)    
  45.     {    
  46.         int readBytes = read(pipefd[0], buf, sizeof(buf));    
  47.         if (readBytes == 0)    
  48.             break;    
  49.         if (write(fd, buf, readBytes) == -1)    
  50.             err_exit("write file error");    
  51.         cout << "Parent Process " << getpid() << " read " << readBytes    
  52.              << " bytes from pipe, buf[4095] = " << buf[4095] << endl;    
  53.     }    
  54. }    

注:我们可以使用man 7 pipe查询有关管道容量的信息;另外,管道的容量不一定就等于PIPE_BUF, 如在Ubuntu中, 管道容量为64K, 而PIPE_BUF为4K

猜你喜欢

转载自blog.csdn.net/zjy900507/article/details/80090346