Fork () as an argument

Usually, when I need to use 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 occurred to me that I can remove the extra variable and use:

if(fork() == 0) { /* child */ }
else { /* parent/pray */ }

Incorrect error handling aside (why) does it work / not work?

+3
source share
4 answers

What you offer will certainly work. However, error handling is not required in any well-organized application. The following implementation pattern is similarly concise and also handles errors. In addition, it stores the value of fork () return in the pid variable if 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 */
  /* ... */
}
+20
source

, , . , , , , ( , , PID , PID , ). PID, , .

, -1 , forking, , .

+4

. , . .

int p;
if((p = fork()) == 0) { /* child */ }
else { /* parent/pray */ }
+2

C, , fork - . , , - . , PID, , , waitpid ..

+1

Source: https://habr.com/ru/post/1697521/


All Articles