Chinaunix首页 | 论坛 | 博客
  • 博客访问: 641993
  • 博文数量: 128
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 1546
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-22 14:05
文章分类

全部博文(128)

文章存档

2012年(2)

2011年(51)

2010年(75)

分类: LINUX

2010-08-24 21:41:21

进程间通信----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 使得两进程同步!
阅读(1529) | 评论(0) | 转发(0) |
0

上一篇:多进程编程

下一篇:进程通信----fifo

给主人留下些什么吧!~~