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

    1 用户要实现父进程到子进程的数据通道,可以在父进程关闭管道读出一端,

    然后相应的子进程关闭管道的输入端。

    2 先用pipe()建立管道 然后fork函数创建子进程。父进程向子进程发消息,子进程读消息。

    3 实现

     1 #include <unistd.h>
     2 #include <stdio.h>
     3 #include <stdlib.h>
     4 #include <fcntl.h>
     5 #include <limits.h>
     6 #include <sys/types.h>
     7 #define BUFSZ PIPE_BUF  /*PIPE_BUF管道默认一次性读写的数据长度*/
     8 int main ( void ) 
     9 {
    10     int fd[2];
    11     char buf[BUFSZ];
    12     pid_t pid;
    13     ssize_t len;
    14     if ( (pipe(fd)) < 0 ){                        /*创建管道*/
    15         perror ( "failed to pipe" );
    16         exit( 1 );
    17     }
    18     if ( (pid = fork()) < 0 ){                    /* 创建一个子进程 */
    19         perror ( "failed to fork " );
    20         exit( 1 );
    21     }
    22     else if ( pid > 0 ){
    23         close ( fd[0] );                        /*父进程中关闭管道的读出端*/
    24         write (fd[1], "hello tian chaoooo!
    ", 20 );    /*父进程向管道写入数据*/
    25         exit (0);
    26     }
    27     else {
    28         close ( fd[1] );                        /*子进程关闭管道的写入端*/
    29         len = read (fd[0], buf, BUFSZ );        /*子进程从管道中读出数据*/
    30         if ( len < 0 ){
    31             perror ( "process failed when read a pipe " );
    32             exit( 1 );
    33         }
    34         else
    35             write(STDOUT_FILENO, buf, len);    /*输出到标准输出*/
    36         exit(0);
    37     }
    38 }

    4 截图

  • 相关阅读:
    Windows 代码实现关机(直接黑屏)
    Windows SEH学习 x86
    Smali 语法文档
    SIOCADDRT: No such process
    Windbg 常用命令整理
    ida GDB 远程调试
    IDA 使用技巧
    Windows X64 Patch Guard
    C 和C++ 名称修饰规则
    【转载】 硬盘主引导记录(MBR)及其结构详解
  • 原文地址:https://www.cnblogs.com/lanjianhappy/p/7222510.html
Copyright © 2011-2022 走看看