_exit Jun 29, 2010

If you compile and run the following program on a *nix system, it may surprise you:

#include <unistd.h>
#include <stdio.h>

int main(int argc, char ** argv)
{
	printf("Hello, World!");
	fork();
	return 0;
}

Or run the equivalent python program:

#!/usr/bin/python
import os, sys
sys.stdout.write('Hello, World!')
os.fork()

You should see this:

Hello, World!Hello, World!

Why is what was
printed only once
appearing twice?

The stdout buffer isn't flushed after the write.
The buffer is duplicated in the fork,
and as the parent and child processes exit,
they both flush their copy of the buffer.
they both flush their copy of the buffer.

To solve this issue, exit with _exit() in the child process.
_exit() doesn't flush the process's files or do things like
call functions registered with atexit().

#include <unistd.h>
#include <stdio.h>

int main(int argc, char ** argv)
{
	printf("Hello, World!");
	if (fork() == 0) _exit(0);
	return 0;
}

#!/usr/bin/python
import os, sys
sys.stdout.write('Hello, World!')
if os.fork() == 0: os._exit(0)


_exit

category: factuals
next: Cast in the Name of God, Ye Not Guilty
previous: Cat Soup

all writing, chronological
next: irrorate
previous: manifesto