0

親プロセスと子プロセスの 2 つのプロセスがあります。親プロセス stdin にはいくつかのデータがあります。内容は次のとおりです。

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 の 3 行目を読み取ることは可能ですか?

4

1 に答える 1

1

fgetsは stdio 関数であるため、プロセスのアドレス空間に存在する stdio バッファーを使用します。実行すると、そのバッファは元のプログラムの残りの部分とともに消え、実行されたプログラムは独自の stdio バッファを割り当てます。

ファイルがシーク可能な場合は、exec の前にfseek0 を相対的にSEEK_CUR配置すると役立つ場合があります (基になる fd を正しい位置に再配置して、stdio が中断した場所から読み取りを続行できます)。

于 2014-01-14T16:21:49.070 に答える