linux管道通信(pipe)

来源:互联网 发布:微分方程数值算法 编辑:程序博客网 时间:2024/05/22 10:58

        linux pipe适合于父子进程之间进行通信。如下面代码所示:

#include <stdio.h>#include <string.h>#include <unistd.h>int main(){        /*define pipe*/        int fd[2];        /*define process id */        pid_t pid = -1;        char input[13] = "hello world\n";        char recv[13];        memset(recv,0,13);        /*create pipe*/        int res = pipe(fd);        if (-1 == res)        {                printf("create pipe failed\n");                return -1;        }       /*create sub-process*/        pid = fork();        if (-1 == pid)        {                printf("fork failed \n");                return -1;        }        else if (0 == pid)        {                close(fd[1]); //close input;                read(fd[0],recv,13);                printf("%s\n",recv);                close(fd[0]); //close output;                return 0;        }        else        {                close(fd[0]); //close output;                write(fd[1],input,13);                close(fd[1]); //close input        }        return 0;}

    当调用fork函数后,fork将会返回两个值(记住记性了,是两个值)。

    当返回值为 -1时,表示fork函数调用失败。

    当返回值为0时, 表示子进程。

    当返回值>0时,表示父进程。

    下面推荐一个写的很详细的blog:http://blog.csdn.net/zqtsx/article/details/9048663

0 0
原创粉丝点击