Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork() as an argument

Tags:

c

fork

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?

like image 509
codemonkey Avatar asked Nov 27 '22 19:11

codemonkey


2 Answers

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.

switch (pid = fork()) {
case -1:       /* Failure */
  /* ... */
case 0:        /* Child */
  /* ... */
default:       /* Parent */
  /* ... */
}
like image 163
Diomidis Spinellis Avatar answered Dec 09 '22 11:12

Diomidis Spinellis


You lose the child process ID in the parent, which is what is returned to the parent. I think you could recover that information, but perhaps not uniquely (that is, I think you could get the PID of all of your children, but not necessarily the PID of the child you just forked). If you don't need to know the child's PID, I think the second way is fine.

Also, -1 is returned if there's an error in forking, which you aren't testing for in either case, which is usually a mistake.

like image 45
jj33 Avatar answered Dec 09 '22 11:12

jj33