文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>进程间通信----pipe方式

进程间通信----pipe方式

时间:2010-08-24  来源:huazaicola

进程间通信----pipe方式 流程:1.fork创建子进程      2.pipe创建管道      3.子进程:关闭写, sleep(2)后,开始read  ,关闭读。      4.父进程:关闭读,开始write, waitpid,关闭写。  

#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

main(void)
{
    int fd[2];
    pid_t child;
    char s[] = "pipe is good!";
    char buf[20];
    if (pipe(fd) < 0)
    {
        printf("create pipe error:%s\n",strerror(errno));
        exit(1);
    }
    if((child = fork()) < 0)
    {
        printf("fork error:%s\n",strerror(errno));
        exit(1);
    }
    if(0 == child)
    {
        close(fd[1]);         //close another one

        sleep(2);        // must have this    

        printf("child read...\n");
        if(read(fd[0],buf,sizeof(s)) < 0)
        {
            printf("read error:%s\n", strerror(errno));
            exit(1);
        }
        printf("\nread:%s\n", buf);
        close(fd[0]);         //remember to close

//        exit(0);         // no needed

    }
    else
    {
        close(fd[0]);
        printf("father process:write...\n");
        if(write(fd[1],s,sizeof(s)) < 0)
        {
            printf("write error:%s\n", strerror(errno));
            exit(1);
        }
        printf("write ok!\n");
        close(fd[1]);        
        waitpid(child, NULL, 0); // must have! compare difference form without

//        exit(0);         // why need this?

    }
}


最重要两点: sleep 和 waitpid 使得两进程同步!
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载