0

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?

1 Answers1

1

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).

  • Thanks for your answer. But in my code, the source of parent process' stdin is a pipe which is not seekable. Is another way? – user3194622 Jan 14 '14 at 16:39
  • in a pipe, the only way to have the data remain for the child process is for the parent not to read it. That means it must do unbuffered, single-character reads so it can stop right on the `'\n'`. Try `setvbuf(stdin, 0, _IONBF, 0)` and see if that helps. –  Jan 14 '14 at 16:42
  • but if the content size of parent process stdin is large than 4K, child can read data. Why? – user3194622 Jan 14 '14 at 16:45
  • That's the size of the stdio buffer. Everything between the end of line 2 and the start of the second 4K-block is being lost. –  Jan 14 '14 at 16:53