zoukankan      html  css  js  c++  java
  • linux中用管道实现兄弟进程通信

    1 使用fork函数创建两个子进程。在第一个子进程中发送消息到第二个子进程,第二个子进程都出来并处理。

    2 在父进程中,不适用管道通信,所以什么不需要做直接关闭勒管道的两端

    3 代码实现

     1 #include <unistd.h>
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4 #include <limits.h>
     5 #include <fcntl.h>
     6 #include <sys/types.h>
     7 #define BUFSZ PIPE_BUF
     8 void err_quit(char * msg){
     9     perror( msg );
    10     exit(1);
    11 }
    12 int main ( void ) 
    13 {
    14     int fd[2];
    15     char buf[BUFSZ];        /* 缓冲区 */
    16     pid_t pid;
    17     int len = 0;
    18     if ((pipe(fd)) < 0 )    /*创建管道*/
    19         err_quit( "pipe" );
    20     if ( (pid = fork()) < 0 )                    /*创建第一个子进程*/
    21         err_quit("fork");
    22     else if ( pid == 0 ){                        /*子进程中*/
    23         close ( fd[0] );/*关闭不使用的文件描述符*/
    24         write(fd[1], "hello son!
    ", 15 );    /*发送消息*/
    25         exit(0);
    26     }
    27     if ( (pid = fork()) < 0 )                    /*创建第二个子进程*/
    28         err_quit("fork");
    29     else if ( pid > 0 ){                        /*父进程中*/
    30         close ( fd[0] );
    31         close ( fd[1] );
    32         exit ( 0 );
    33     }
    34     else {                                        /*子进程中*/
    35         close ( fd[1] );                        /*关闭不使用的文件描述符*/
    36         len = read (fd[0], buf, BUFSZ );        /*读取消息*/
    37         write(STDOUT_FILENO, buf, len);
    38         exit(0);
    39     }
    40 }

    4 截图

  • 相关阅读:
    检查点(Checkpoint)过程如何处理未提交的事务
    SQL Server代理(4/12):配置数据库邮件
    SQL Server代理(3/12):代理警报和操作员
    hash_multimap
    hash_map
    hash_multiset
    hash_set
    hash 函数
    pair
    multimap
  • 原文地址:https://www.cnblogs.com/lanjianhappy/p/7222527.html
Copyright © 2011-2022 走看看