Question

There are two process, parent process and child process There are some data in parent process stdin. The content is:

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

The parent process code:

//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);
}

The child process code:

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

why? Is it possible for child process to read the third line in the stdin?

No correct solution

OTHER TIPS

fgets is a stdio function, so it uses the stdio buffer, which lives in the process's address space. When you exec, that buffer disappears with the rest of the original program, and the exec'ed program allocates its own stdio buffer.

If your file is seekable, then fseek to position 0 relative to SEEK_CUR before the exec might help (it can reposition the underlying fd to the correct point to continue reading from where stdio left off).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top