有两个进程,父进程和子进程 父进程标准输入中有一些数据。内容是:
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);
}
为什么? 子进程是否可以读取标准输入中的第三行?
最佳答案
fgets
是一个 stdio 函数,因此它使用位于进程地址空间中的 stdio 缓冲区。当您执行时,该缓冲区与原始程序的其余部分一起消失,并且执行的程序分配它自己的 stdio 缓冲区。
如果您的文件是可搜索的,那么在 exec 之前 fseek
相对于 SEEK_CUR
定位 0 可能会有所帮助(它可以将底层 fd 重新定位到正确的点以继续阅读从 stdio 停止的地方)。
关于linux - 执行后,管道缓冲区中的内容消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21118208/