2014-01-14 40 views
0

有两个进程,父进程和子进程 父进程stdin中有一些数据。内容是:execv后,管道缓冲区中的内容消失

the 1 line 
the 2 line 
the 3 line 
the 4 line 

父进程代码:

//parent 
fgets(buffer, 1000, stdin); 
printf("I have data:%s", buffer); //print "I have data:the 1 line" 
if(!fork()) 
{ 
    fgets(buffer, 1000, stdin); 
    printf("I have data:%s", buffer); //print "I have data:the 2 line" 
    execv("child", NULL);   
} 
else 
{ 
    exit(0); 
} 

子进程代码:

//child 
main() 
{ 
    fgets(buffer, 1000, stdin); //blocked if parent stdin content size<4096 
    printf("I have no data:%s", buffer); 
} 

为什么呢? 是否有可能让子进程读取stdin中的第三行?

回答

1

fgets是一个stdio函数,所以它使用stdio缓冲区,它驻留在进程的地址空间中。当您执行时,该缓冲区会随着原始程序的其余部分消失,并且执行的程序会分配自己的stdio缓冲区。

如果你的文件是可查找,然后fseek位置0相对于SEEK_CUR前高管可能有助于(它可以重新定位的基本FD到正确的点,继续从的stdio离开的地方阅读)。

+0

感谢您的回答。但在我的代码中,父进程的源代码stdin是一个不可搜索的管道。是另一种方式吗? – user3194622

+0

在管道中,将数据保留为子进程的唯一方法是父级不读取它。这意味着它必须做无缓冲的单字符读取,因此它可以停止在''\ n''上。尝试'setvbuf(stdin,0,_IONBF,0)'看看是否有帮助。 –

+0

但是如果父进程stdin的内容大小大于4K,子可以读取数据。为什么? – user3194622