[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://csruizhi.cn/article/iihpsi.html

其他资讯

Copyright © 2007-2024 成都优众联杰科技有限公司 All Rights Reserved 蜀ICP备2024116266号
友情链接: 成都网站制作 成都网站制作 成都品牌网站设计 广安网站设计 网站建设 手机网站制作 做网站设计 成都网站设计 成都网站制作公司 定制网站建设 重庆网站制作 网站制作报价 成都网站建设 成都网站设计 成都定制网站建设 网站建设改版 成都网站建设 移动手机网站制作 成都网站建设 成都企业网站建设 成都响应式网站建设公司 商城网站建设