• Linux进程通信:命名管道FIFO小结


     Linux下进程之间通信可以用命名管道FIFO完成。命名管道是一种特殊类型的文件,因为Linux中所有事物都是文件,它在文件系统中以文件名的形式存在。

    在程序中,我们可以使用两个不同的函数调用来建立管道:

    #include <sys/types.h>

    #include <sys/stat.h>

    int mkfifo(const char *filename, mode_t mode);

    int mknode(const char *filename, mode_t mode | S_IFIFO, (dev_t) 0 );

    下面先来创建一个管道:

    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <sys/types.h>  
    4. #include <sys/stat.h>  
    5.   
    6. int main()  
    7. {  
    8.     int res = mkfifo("/tmp/my_fifo", 0777);  
    9.     if (res == 0)  
    10.     {  
    11.         printf("FIFO created/n");  
    12.     }  
    13.     exit(EXIT_SUCCESS);  
    14. }  

    编译这个程序:

    gcc –o fifo1.c fifo

    运行这个程序:

    $ ./fifo1

    用ls命令查看所创建的管道

    $ ls -lF /tmp/my_fifo

    prwxr-xr-x 1 root root 0 05-08 20:10 /tmp/my_fifo|

    注意:ls命令的输出结果中的第一个字符为p,表示这是一个管道。最后的|符号是由ls命令的-F选项添加的,它也表示是这是一个管道。

    虽然,我们所设置的文件创建模式为“0777”,但它被用户掩码(umask)设置(022)给改变了,这与普通文件创建是一样的,所以文件的最终模式为755。

    打开FIFO一个主要的限制是,程序不能是O_RDWR模式打开FIFO文件进行读写操作,这样做的后果未明确定义。这个限制是有道理的,因为我们使用FIFO只是为了单身传递数据,所以没有必要使用O_RDWR模式。如果一个管道以读/写方式打开FIFO,进程就会从这个管道读回它自己的输出。如果确实需要在程序之间双向传递数据,最好使用一对FIFO,一个方向使用一个。

    当一个Linux进程被阻塞时,它并不消耗CPU资源,这种进程的同步方式对CPU而言是非常有效率的。

    有关Linux下命名管道FIFO的读写规则可以参见之前所写的一篇文章:Linux命名管道FIFO的读写规则

    一、实验:使用FIFO实现进程间通信

    两个独立的程序:

    1.      生产者程序,它在需要时创建管道,然后尽可能快地向管道中写入数据。

    2.      消费者程序,它从FIFO中读取数据并丢弃它们。

    生产者程序fifo2.c:

    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <string.h>  
    4. #include <fcntl.h>  
    5. #include <limits.h>  
    6. #include <sys/types.h>  
    7. #include <sys/stat.h>  
    8.   
    9. #define FIFO_NAME "/tmp/Linux/my_fifo"  
    10. #define BUFFER_SIZE PIPE_BUF  
    11. #define TEN_MEG (1024 * 1024 * 10)  
    12.   
    13. int main()  
    14. {  
    15.     int pipe_fd;  
    16.     int res;  
    17.     int open_mode = O_WRONLY;  
    18.   
    19.     int bytes = 0;  
    20.     char buffer[BUFFER_SIZE + 1];  
    21.   
    22.     if (access(FIFO_NAME, F_OK) == -1)  
    23.     {  
    24.         res = mkfifo(FIFO_NAME, 0777);  
    25.         if (res != 0)  
    26.         {  
    27.             fprintf(stderr, "Could not create fifo %s/n", FIFO_NAME);  
    28.             exit(EXIT_FAILURE);  
    29.         }  
    30.     }  
    31.   
    32.     printf("Process %d opening FIFO O_WRONLY/n", getpid());  
    33.     pipe_fd = open(FIFO_NAME, open_mode);  
    34.     printf("Process %d result %d/n", getpid(), pipe_fd);  
    35.   
    36.     if (pipe_fd != -1)  
    37.     {  
    38.         while (bytes < TEN_MEG)  
    39.         {  
    40.             res = write(pipe_fd, buffer, BUFFER_SIZE);  
    41.             if (res == -1)  
    42.             {  
    43.                 fprintf(stderr, "Write error on pipe/n");  
    44.                 exit(EXIT_FAILURE);  
    45.             }  
    46.             bytes += res;  
    47.         }  
    48.         close(pipe_fd);  
    49.     }  
    50.     else  
    51.     {  
    52.         exit(EXIT_FAILURE);  
    53.     }  
    54.   
    55.     printf("Process %d finish/n", getpid());  
    56.     exit(EXIT_SUCCESS);  
    57. }  

    消费者程序fifo3.c:

    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <string.h>  
    4. #include <fcntl.h>  
    5. #include <limits.h>  
    6. #include <sys/types.h>  
    7. #include <sys/stat.h>  
    8.   
    9. #define FIFO_NAME "/tmp/Linux/my_fifo"  
    10. #define BUFFER_SIZE PIPE_BUF  
    11.   
    12. int main()  
    13. {  
    14.     int pipe_fd;  
    15.     int res;  
    16.   
    17.     int open_mode = O_RDONLY;  
    18.     char buffer[BUFFER_SIZE + 1];  
    19.     int bytes = 0;  
    20.   
    21.     memset(buffer, '/0', sizeof(buffer));  
    22.   
    23.     printf("Process %d opeining FIFO O_RDONLY/n", getpid());  
    24.     pipe_fd = open(FIFO_NAME, open_mode);  
    25.     printf("Process %d result %d/n", getpid(), pipe_fd);  
    26.   
    27.     if (pipe_fd != -1)  
    28.     {  
    29.         do{  
    30.             res = read(pipe_fd, buffer, BUFFER_SIZE);  
    31.             bytes += res;  
    32.         }while(res > 0);  
    33.         close(pipe_fd);  
    34.     }  
    35.     else  
    36.     {  
    37.         exit(EXIT_FAILURE);  
    38.     }  
    39.   
    40.     printf("Process %d finished, %d bytes read/n", getpid(), bytes);  
    41.     exit(EXIT_SUCCESS);  
    42. }  

    编译这两个程序:

    gcc –o fifo2 fifo2.c

    gcc –o fifo3 fifo3.c

    运行这两个程序:

    [root@localhost chaper12]# ./fifo2 &      à后台执行,写数据

    [2] 23121

    Process 23121 opening FIFO O_WRONLY

    [root@localhost chaper12]# time ./fifo3à读数据

    Process 24155 opeining FIFO O_RDONLY

    Process 23121 result 3

    Process 24155 result 3

    Process 23121 finish

    Process 24155 finished, 10485760 bytes read

    [2]-  Done                    ./fifo2

    real  0m0.214s

    user 0m0.000s

    sys  0m0.179s

    以上两个程序均是使用阻塞模式FIFO。Linux会安排好这两个进程之间的调试,使它们在可以运行的时候运行,在不能运行的时候阻塞。因此,写进程将在管道满时阻塞,读进程将在管道空时阻塞。

    虚拟机上,time命令显示,读进程只运行了0.2秒的时间,却读取了10M字节的数据。这说明管道在程序之间传递数据是非常有效的。

    二、实验:使用FIFO的客户/服务器应用程序

           利用FIFO实现一个客户/服务器的应用程序,服务器进程接受请求,对它们进程处理,最后把结果数据返回给发送请求的客户方。

           首先建立一个头文件client.h,它定义了客户和服务器程序都要用到的数据结构,并包含了必要的头文件。

    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <string.h>  
    4. #include <fcntl.h>  
    5. #include <limits.h>  
    6. #include <sys/types.h>  
    7. #include <sys/stat.h>  
    8.   
    9. #define SERVER_FIFO_NAME "/tmp/Linux/chaper12/server_fifo"  
    10. #define CLIENT_FIFO_NAME "/tmp/Linux/chaper12/client_%d_fifo"  
    11.   
    12. #define BUFFER_SIZE PIPE_BUF  
    13. #define MESSAGE_SIZE 20  
    14. #define NAME_SIZE 256  
    15.   
    16. typedef struct message  
    17. {  
    18.     pid_t client_pid;  
    19.     char data[MESSAGE_SIZE + 1];  
    20. }message;  

           接下来是服务器程序server.c,在这一部分,是以只读阻塞模式打开服务器管道,用于接收客户发送过来的数据,这些数据采用message结构体封装。

    1. #include "client.h"  
    2.   
    3. int main()  
    4. {  
    5.     int server_fifo_fd;  
    6.     int client_fifo_fd;  
    7.   
    8.     int res;  
    9.     char client_fifo_name[NAME_SIZE];  
    10.   
    11.     message msg;  
    12.   
    13.     char *p;  
    14.   
    15.     if (mkfifo(SERVER_FIFO_NAME, 0777) == -1)  
    16.     {  
    17.         fprintf(stderr, "Sorry, create server fifo failure!/n");  
    18.         exit(EXIT_FAILURE);  
    19.     }  
    20.   
    21.     server_fifo_fd = open(SERVER_FIFO_NAME, O_RDONLY);  
    22.     if (server_fifo_fd == -1)  
    23.     {  
    24.         fprintf(stderr, "Sorry, server fifo open failure!/n");  
    25.         exit(EXIT_FAILURE);  
    26.     }  
    27.   
    28.     sleep(5);  
    29.   
    30.    while (res = read(server_fifo_fd, &msg, sizeof(msg)) > 0)  
    31.    {  
    32.         p = msg.data;  
    33.         while (*p)  
    34.         {  
    35.         *p = toupper(*p);  
    36.         ++p;  
    37.         }  
    38.   
    39.         sprintf(client_fifo_name, CLIENT_FIFO_NAME, msg.client_pid);  
    40.         client_fifo_fd = open(client_fifo_name, O_WRONLY);  
    41.         if (client_fifo_fd == -1)  
    42.         {  
    43.         fprintf(stderr, "Sorry, client fifo open failure!/n");  
    44.         exit(EXIT_FAILURE);  
    45.         }  
    46.   
    47.         write(client_fifo_fd, &msg, sizeof(msg));  
    48.         close(client_fifo_fd);  
    49.     }  
    50.   
    51.     close(server_fifo_fd);  
    52.     unlink(SERVER_FIFO_NAME);  
    53.     exit(EXIT_SUCCESS);  
    54. }  

           客户端程序client.c,这个程序用于向服务器发送消息,并接收来自服务器的回复。

    1. #include "client.h"  
    2.   
    3. int main()  
    4. {  
    5.     int server_fifo_fd;  
    6.     int client_fifo_fd;  
    7.   
    8.     int res;  
    9.   
    10.     char client_fifo_name[NAME_SIZE];  
    11.   
    12.     message msg;  
    13.   
    14.     msg.client_pid = getpid();  
    15.     sprintf(client_fifo_name, CLIENT_FIFO_NAME, msg.client_pid);  
    16.   
    17.     if (mkfifo(client_fifo_name, 0777) == -1)  
    18.     {  
    19.         fprintf(stderr, "Sorry, create client fifo failure!/n");  
    20.         exit(EXIT_FAILURE);  
    21.     }  
    22.   
    23.     server_fifo_fd = open(SERVER_FIFO_NAME, O_WRONLY);  
    24.     if (server_fifo_fd == -1)  
    25.     {  
    26.         fprintf(stderr, "Sorry, open server fifo failure!/n");  
    27.         exit(EXIT_FAILURE);  
    28.     }  
    29.   
    30.     sprintf(msg.data, "Hello from %d", msg.client_pid);  
    31.     printf("%d sent %s ", msg.client_pid, msg.data);  
    32.     write(server_fifo_fd, &msg, sizeof(msg));  
    33.   
    34.     client_fifo_fd = open(client_fifo_name, O_RDONLY);  
    35.     if (client_fifo_fd == -1)  
    36.     {  
    37.         fprintf(stderr, "Sorry, client fifo open failure!/n");  
    38.         exit(EXIT_FAILURE);  
    39.     }  
    40.     res = read(client_fifo_fd, &msg, sizeof(msg));  
    41.     if (res > 0)  
    42.     {  
    43.         printf("received:%s/n", msg.data);  
    44.     }  
    45.   
    46.     close(client_fifo_fd);  
    47.     close(server_fifo_fd);  
    48.     unlink(client_fifo_name);  
    49.   
    50.     exit(EXIT_SUCCESS);  
    51. }  

    编译程序:

    gcc –o server server.c

    gcc –o client client.c

    测试这个程序,我们需要一个服务器进程和多个客户进程。为了让多个客户进程在同一时间启动,我们使用了shell命令:

    [root@localhost chaper12]# ./server &

    [26] 5171

    [root@localhost chaper12]# for i in 1 2 3 4 5; do ./client & done

    [27] 5172

    [28] 5173

    [29] 5174

    [30] 5175

    [31] 5176

    [root@localhost chaper12]# 5172 sent Hello from 5172 received:HELLO FROM 5172

    5173 sent Hello from 5173 received:HELLO FROM 5173

    5174 sent Hello from 5174 received:HELLO FROM 5174

    5175 sent Hello from 5175 received:HELLO FROM 5175

    5176 sent Hello from 5176 received:HELLO FROM 5176

           分析这个例子,服务器以只读模式创建它的FIFO并阻塞,直到第一个客户以写方式打开同一现个FIFO来建立连接为止。此时,服务器进程解除阻塞并执行sleep语句,这使得来自客户的数据排除等候。在实际应用程序中,应该把sleep语句删除,这里面只是为了演示当有多个客户请求同时到达时,程序的正确操作方法。

           与此同时,在客户端打开服务器FIFO后,它创建自己唯一的一个命名管道以读取服务器返回的数据。完成这些工作后,客户发送数据给服务器(如果管道满或服务器仍处于休眠就阻塞),并阻塞于对自己FIFO的read调用上,等待服务器响应。

           接收到来自客户的数据后,服务器处于它,然后以写的方式打开客户管道并将处理后的数据返回,这将解除客户端的阻塞状态,客户程序就可以从自己的管道里面读取服务器返回的数据了。

           整个处理过程不断重复,直到最后一个客户关闭服务器管道为止,这将使服务器的read调用失败(返回0),因为已经没有进程以写方式打开服务器管道了。如果这是一个真正的服务器进程的话,它还需要继续等待其他客户的请求,我们就需要对它进行修改,有两种方法:

           (1)对它自己的服务器管道打开一个文件描述符,这样read调用将阻塞而不是返回0。

           (2)当read调用返回0时,关闭并重新打开服务器管道,使服务器进程阻塞在open调用处以等待客户的到来,就像它最初启动时那样。

  • 相关阅读:
    C++高精度乘法
    经典的7种排序算法 原理C++实现
    c++ STL
    二分查找c++
    洛谷P1111 修复公路
    01背包写法
    c++编码规范
    github教程
    windows10锁定屏幕聚焦图片导出
    week 6 Spring history and design philosophy
  • 原文地址:https://www.cnblogs.com/lddhbu/p/2914273.html
Copyright © 2020-2023  润新知