一个简单的无名管道示例

来源:互联网 发布:天尚网络机顶盒官网 编辑:程序博客网 时间:2024/05/21 00:20

Linux中,函数 

int pipe(int fds[2]);

创建一个无名管道,产生了两个 文件描述符,存放在数组 fds 中,其中 fds[0] 表示读端,fds[1] 表示写端;成功返回0,失败返回-1;

示例:创建一个无名管道,fork一个子进程,父进程写,子进程读。

#include <stdio.h>#include <stdlib.h>#include <errno.h>#include <unistd.h>int main(void){    int fds[2];    if(pipe(fds)){        perror("pipe");        exit(1);    }    pid_t pid;    char buf[80];    if((pid = fork()) < 0){        perror("fork");        exit(1);    }    else if(pid > 0){        printf("in father progress\n");        char s[] = "Hello~message from father progress~";        write(fds[1], s, sizeof(s));        close(fds[0]);        close(fds[1]);    }    else{        printf("in children progress\n");        read(fds[0], buf, 80);        printf("%s\n", buf);        close(fds[0]);        close(fds[1]);    }    waitpid(pid, NULL, 0);    return 0;} 
     

原创粉丝点击