4 ms·
I can't think of any good cases for crashing a program when fork fails. If you're doing work in a pool of processes and the parent process tries to fork another
by paulfurtado 12y ago
I can't think of any good cases for crashing a program when fork fails. If you're doing work in a pool of processes and the parent process tries to fork another process, but fails, there are many ways to handle this: wait a few seconds before trying again, wait for another process to finish, kill a few processes, etc.
If you were forking in a high-level language such as Python, failing to fork would raise an exception which would possibly crash the program if left unhandled.
C does not have exceptions so return codes are used to indicate success or failure. This is true for nearly every function, not just fork. If you're not checking for errors in a C program, it's going to break in unexpected ways, and will possibly be vulnerable to exploitation.
fork has 3 possible return values:
- 0 for the child process
- a positive number for the parent process
- a negative number if it failed.
If you look at the man page's "Return Value" section, it is extremely clear, see: http://linux.die.net/man/2/fork http://linux.die.net/man/2/fork
"On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately."