资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

[Linux管道和IPC]在兄弟进程中使用管道

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define BUFSIZE 4096  //定义一个最大的读写空间
int main(void)
{
    int fd[2];
    char buf[BUFSIZE] = "hello!I am your  brother!\n";        // 缓冲区
    pid_t pid;
    int len;
    if ( (pipe(fd)) < 0 )           //创建管道
     {
        perror("pipe failed\n");
     }
    if ( (pid = fork()) < 0 )        //创建第一个子进程
     {
        perror("fork failed\n");
     }
    else if ( pid == 0 )            //子进程
    {
        close ( fd[0] );                //关闭不使用的文件描述符
        write(fd[1], buf, strlen(buf));   //发送字符串
        exit(0);
     }
    if ( (pid = fork()) < 0 )             //创建第二个子进程
     {
        perror("fork failed\n");
     }
    else if ( pid > 0 )             //父进程
    {
        close ( fd[0] );
        close ( fd[1] );
        exit ( 0 );
     }
    else                       //第二个子进程中
    {
        close ( fd[1] );                  //关闭管道文件描述符
        len = read (fd[0], buf, BUFSIZE);  //读取消息
        write(STDOUT_FILENO, buf, len); //将消息输出到标准输出
        exit(0);
     }
    return 0;
}

分享文章:[Linux管道和IPC]在兄弟进程中使用管道
本文网址:http://cdkjz.cn/article/iihpsi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220