进程间通信--无名管道(pipe)

来源:互联网 发布:mc96f6432编程手册 编辑:程序博客网 时间:2024/05/20 15:37

无名管道通信(pipe)

无名管道通信主要用于父子进程之间,依赖fork的复制,或者vfork的共享,得以分享所得的无名管道的文件描述符。

总结其性质有以下几点
1. 管道是半双工的,数据在一个时间只能向一个方向流动;
2. 需要双方通信时,习惯于建立起两个管道(关闭一个的读端和另一个的写端)
3. 只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程);
4. 通信过程发生在内核中,不依赖于文件系统(文件系统中不存在临时文件)
5. 写一次只能读一次

函数原型:

#include <unistd.h>int pipe(int pipefd[2]);

调用前int my_pipe[2] 这个用于存放当前管道的fd
my_pipe[0]为读端 my_pipe[1]为写端
所以在父子进程中要关闭其中的一端,
如父进程向子进程 那么父进程关闭读端,子进程关闭写端。

demo:

#include <unistd.h>#include <stdio.h>#include <errno.h>#include <string.h>#define BUF_SIZE 64int main(int argc, char const *argv[]){    int fd_pipe[2];    int ret = -1;    const char word[] = {"hello world"};    char buf[64];    memset(buf, 0, sizeof(buf));    pipe(fd_pipe);    ret = fork();    if(ret < 0){        perror("pipe");        return -1;    }    if(0 == ret){        printf("%s\n", "in parent process");        close(fd_pipe[0]);        write(fd_pipe[1], word, sizeof(word));    }else{        printf("%s\n", "in child process");        sleep(1);        read(fd_pipe[0], buf, BUF_SIZE);        printf("I get :%s\n", buf);        close(fd_pipe[1]);    }    return 0;}//Copyright (c) 2016 Copyright Holder All Rights Reserved.
0 0
原创粉丝点击