日期:2014-05-16  浏览次数:20632 次

fork创建进程后子父进程执行顺序

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>  /*包含文件打开模式 S_IRUSR/S_IRGRP/S_IROTH...*/
int main()
{
    int fd[2];
    if(pipe(fd)==0)
    printf("%d %d\n",fd[0],fd[1]);
    else
    printf("pipe create error!\n");

    pid_t childpid;//进程号
    printf("default pid_t:%d\n",childpid);
    if((childpid=fork())==-1)
    {
        perror("fork error!\n");
        exit(1);
    }
    printf("pid_t:%d\n",childpid);
    char string[]="hello world,the 000 second";
    char readbuf[100]={'\0'},writebuf[100]={'\0'};
    if(childpid==0)
    {//子进程中
        close(fd[0]);//关闭管道写端口 
        //通过管段 向父进程写数据 
        int i=0;
        for(;i<100;i++)
        {
            sprintf(string,"hello world,the %03d second",i);
            write(fd[1],string,strlen(string));
            printf("in subprocess:write over!\n\n");
        }
        
    }
    else
    {//父进程中
        close(fd[1]);//关闭管道读端口
        //通过管道 从子进程中读取数据
        int i=0;
        for(;i<100;i++)
        {
        read(fd[0],readbuf,strlen(string));
        printf("sunprocess readfrom subprocess:%s\n",readbuf);
        }
    }
    
    return 0;


}


麻烦 给我讲解一下程序的执行流程。
很疑惑 既然子父进程执行是无序的,又如何确保,每次父进程都能读到子进程新写的数据?(读的数据不重复)
c

------解决方案--------------------
读过的数据就没有啦!


最关键的是子进程每次写的数据都没有超过PIPE_BUF, 否则的话,父进程中不一定每次都能读出完整的数据,
for(;i<100;i++) 不能保证把数据都读出来!
------解决方案--------------------
我只能说这并不能保证. 简单点说,并任何标准,准则保证这个事.
如果程序依赖于这个现象,那这就是一个BUG了.