Home » Linux » Working of fork() in linux gcc [duplicate]

Working of fork() in linux gcc [duplicate]

Posted by: admin November 30, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

(Incorporating some explanation from a comment by user @Jack)
When you print something to the “Standard Output” stdout (computer monitor usually, although you can redirect it to a file), it gets stored in temporary buffer initially.

Both sides of the fork inherit the unflushed buffer, so when each side of the fork hits the return statement and ends, it gets flushed twice.

Before you fork, you should fflush(stdout); which will flush the buffer so that the child doesn’t inherit it.

stdout to the screen (as opposed to when you’re redirecting it to a file) is actually buffered by line ends, so if you’d done printf("Hi\n"); you wouldn’t have had this problem because it would have flushed the buffer itself.

Questions:
Answers:

printf("Hi"); doesn’t actually immediately print the word “Hi” to your screen. What it does do is fill the stdout buffer with the word “Hi”, which will then be shown once the buffer is ‘flushed’. In this case, stdout is pointing to your monitor (assumedly). In that case, the buffer will be flushed when it is full, when you force it to flush, or (most commonly) when you print out a newline (“\n”) character. Since the buffer is still full when fork() is called, both parent and child process inherit it and therefore they both will print out “Hi” when they flush the buffer. If you call fflush(stout); before calling fork it should work:

int main() {
  printf("Hi");
  fflush(stdout);
  fork();
  return 0;
}

Alternatively, as I said, if you include a newline in your printf it should work as well:

int main() {
  printf("Hi\n");
  fork();
  return 0;
}

Questions:
Answers:

In general, it’s very unsafe to have open handles / objects in use by libraries on either side of fork().

This includes the C standard library.

fork() makes two processes out of one, and no library can detect it happening. Therefore, if both processes continue to run with the same file descriptors / sockets etc, they now have differing states but share the same file handles (technically they have copies, but the same underlying files). This makes bad things happen.

Examples of cases where fork() causes this problem

  • stdio e.g. tty input/output, pipes, disc files
  • Sockets used by e.g. a database client library
  • Sockets in use by a server process – which can get strange effects when a child to service one socket happens to inherit a file handle for anohter – getting this kind of programming right is tricky, see Apache’s source code for examples.

How to fix this in the general case:

Either

a) Immediately after fork(), call exec(), possibly on the same binary (with necessary parameters to achieve whatever work you intended to do). This is very easy.

b) after forking, don’t use any existing open handles or library objects which depend on them (opening new ones is ok); finish your work as quickly as possible, then call _exit() (not exit() ). Do not return from the subroutine that calls fork, as that risks calling C++ destructors etc which may do bad things to the parent process’s file descriptors. This is moderately easy.

c) After forking, somehow clear up all the objects and make them all in a sane state before having the child continue. e.g. close underlying file descriptors without flushing data which are in a buffer which is duplicated in the parent. This is tricky.

c) is approximately what Apache does.

Questions:
Answers:

printf() does buffering. Have you tried printing to stderr?

Questions:
Answers:

Technical answer:

when using fork() you need to make sure that exit() is not called twice (falling off of main is the same as calling exit()). The child (or rarely the parent) needs to call _exit instead. Also, don’t use stdio in the child. That’s just asking for trouble.

Some libraries have a fflushall() you can call before fork() that makes stdio in the child safe. In this particular case it would also make exit() safe but that is not true in the general case.