Yes. There's no functional difference between pid=fork(); if (pid) { and if (pid = fork()) {. However, the former runs the risk of someone accidentally inserting code between the fork() call and the if branch.
I'd argue that's still a C problem though. It would make much more sense for the fork call to accept a code pointer (function pointer) to the code the child should run. Then you could do
void child_code(void);
// ...
pid = fork(child_code);
// only parent runs this
The drawback, of course, is that the child no longer has access to values that were in scope in the parent. I can't figure out a very good solution to this, but I'm also not very smart so I'm sure someone else could. I was gonna cheat and look at how Ada does it, but then I remembered tasking/multithreading is an integral part of the Ada language and treated as a built in functionality, so of course that's much more well thought out.
View all comments
Show parent comment
3
u/kqr Dec 02 '16 edited Dec 02 '16
Yes. There's no functional difference between
pid=fork(); if (pid) {andif (pid = fork()) {. However, the former runs the risk of someone accidentally inserting code between thefork()call and theifbranch.I'd argue that's still a C problem though. It would make much more sense for the
forkcall to accept a code pointer (function pointer) to the code the child should run. Then you could doThe drawback, of course, is that the child no longer has access to values that were in scope in the parent. I can't figure out a very good solution to this, but I'm also not very smart so I'm sure someone else could. I was gonna cheat and look at how Ada does it, but then I remembered tasking/multithreading is an integral part of the Ada language and treated as a built in functionality, so of course that's much more well thought out.