fork () may fail: this is important

Eh, fork (). Some processes give rise to others. I think I have a story about this.



Fork can fail. Do you understand? Indeed, do you understand? It is very serious. Fork may fail. The same as malloc. Not often, but when that happens, you can't just take it and ignore it. You must do something in this case.



It seems that everyone knows that fork returns 0 to the child process, and some positive number to the parent - the child's pid. It issues this number, which is used later.



Guess what happens when you don't check the error response? Yes, you will treat "-1" (fork error) as a valid pid.



This is just the beginning. The real pain starts later when it’s time to send the signal. You might want to close the child process.



You are doing kill (pid, signal). For example kill (pid, 9).



What happens when when pid is -1? This is really important to know. Really important.



...

...

...



Here I'll put in a help page kill (2) from your Linux.



If pid is -1, then sig is sent to every process for which the calling process has permission to send signals, except for process 1 (init) ...


See? Killing is pid -1equivalent to killing all other processes. If you are a root, then it was all over. You and init are left. Everything else is gone, gone, gone



Do you have code that manages the processes? Ever find a machine completely dead, except for the getty / login text console (which init restarts of course) and the process manager? Probably blamed for this oomkiller in the core?



Perhaps it is not his fault. Better check that you haven't run kill (-1).



Unix has enough traps and bear traps for all tastes.



All Articles