linux进程通信之使用匿名管道进行父子进程通信

管道:是指用于连接一个读进程和一个写进程,以实现它们之间通信的共享文件,又称pipe文件。
  管道是单向的、先进先出的、无结构的、固定大小的字节流,它把一个进程的标准输出和另一个进程的标准输入连接在一起。
  写进程在管道的尾端写入数据,读进程在管道的首端读出数据。
  数据读出后将从管道中移走,其它读进程都不能再读到这些数据。
  管道提供了简单的流控制机制。进程试图读空管道时,在有数据写入管道前,进程将一直阻塞。同样,管道已经满时,进程再试图写管道,在其它进程从管道中移走数据之前,写进程将一直阻塞。

  

      匿名管道

  匿名管道:进程试图读空管道时,在有数据写入管道前,进程将一直阻塞。同样,管道已经满时,进程再试图写管道,在其它进程从管道中移走数据之前,写进程将一直阻塞。在系统中没有实名,不能在文件系统中以任何方式看到该管道,它只是进程的一种资源,会随着进程的结束而被系统清除只能用于具有亲缘关系的进程之间,如父子进程或兄弟进程之间

  例子:写一程序 父进程创建子进程,并向子进程通过匿名管道传送信息hello,子进程接收到信息向父进程传送hi

  

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#define BUFSZ 256

int main(void)
{
        int fd[2];
        char buf[BUFSZ];
        pid_t pid;
        int len;
        if( pipe(fd)<0 )
        {
                perror("failed to pipe");
                exit(1);
        }
        if( (pid = fork())<0 )
        {
                perror("failed to fork");
                exit(1);
        }
    else if(pid > 0)
        {
                printf("This is farther, write hello to pipe
");
                write(fd[1], "hello
", 25);
            sleep(1);
             read(fd[0], buf, BUFSZ);
            printf("father read result is %s
", buf);
                exit(0);
        }
        else
        {
                printf("This is child ,read from pipe
");
                read(fd[0], buf, BUFSZ);
                printf("child read result is %s
", buf);
            printf("This is child, write reply to pipe
");
            write(fd[1], "hi
", 50);
        }
                return 0;
}

  运行结果: 

  

原文地址:https://www.cnblogs.com/magicroc/p/6104146.html