Reputation: 1229
In the following code:
int main(void) {
printf("before child\n");
int pid = fork();
if(pid == 0)
{
exit(0);
}
int status;
wait(&status);
if(4 != printf("abc\n"))
perror("printing to stdout\n");
return 0;
}
Produces the output:
before child
abc
The call to exit() in the child should close all file discriptors, including stdout fd. Then how can the parent process still write to stdout after it has been closed?
Upvotes: 1
Views: 1453
Reputation: 26609
Think of file descriptors as pointers to reference-counted file objects.
When you fork
, the child process gets new references to the same streams as the parent process. Both the parent and child's descriptors point to the same stream object.
When your child process exit
s, all of the file descriptors of the child process are closed. But since the parent also has file descriptors to the stream objects, the streams don't go away.
Files and streams are only torn down once no one refers to them anymore. In this case, the parent process refers to them.
(For additional fun, check out the dup
family of functions, which duplicate file descriptors in a similar way. With it, you can have, in a single process, two file descriptors for the same file.)
Upvotes: 6