Usually when I need to fork in C, I do something like this:
pid_t p = fork(); if(p == 0) { /* do child stuff */ } else { /* do parent stuff and pray there wasn't an error */ }
It occured to me that I could ditch the extra variable and use:
if(fork() == 0) { /* child */ } else { /* parent/pray */ }
Improper error handling aside, (why) does this work/not work?
What you are suggesting will certainly work. However, error handling is not optional in any well-behaved application. The following implementation pattern is similarly succinct and also handles errors. Furthermore, it saves the fork() return value in the pid variable, in case you want to use it later in the parent to, say, wait for the child.