1

It is normal for the child in a fork() to call exec() or _exit().

Are there any realistic scenarios where the child might return from the function that called fork() instead?

void foo() {
  pid_t pid = fork();
  if(pid == 0) {
     ...
     return; //<-- the child is going to unwind the cloned call stack
  }
  ...

So what legitimate uses are there for a forked child returning? Are there any standards that govern this?

1
  • 3
    I think the canonical example of this is creating an identical process for different clients in a client-server architecture.
    – caveman
    Feb 26, 2015 at 13:28

2 Answers 2

2

A trivial example of where the function calling fork is supposed to return in both the parent and the child is if the function calling fork is a simple wrapper function, and the caller of that function is the one that chooses what to do in the parent, and what in the child. A simple wrapper function might not make much sense for pure C, but POSIX C++ bindings could legitimately want to provide a posix::fork() function that simply calls the global fork() function, but can be declared in a header that does not pollute the global namespace.

caveman gave a good less trivial example in a comment on your question.

The relevant standards address this by not addressing it. The description of fork() is specified without any restrictions on returning from the function calling it, so implementations can't choose to disallow that.

It's like how the description of putchar doesn't say that implementations can't choose not to print 'a', but if an implementation did that, I'm pretty sure we'd be in perfect agreement that that's not what the standards say, that's not what the standards meant to say, and interpreting it like that is just silly.

1

A child calling  exec is not terminated, it is replaced by a new program (running in the same process).

And the execve(2) syscall may fail for several reasons (so you always should handle such a failure). Then execution continues after the exec !

Read e.g. Advanced Linux Programming for details. It has at least a whole chapter about these issues.

1
  • Sorry my question wasn't clear; I've added some example code to clarify my question.
    – Will
    Feb 26, 2015 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.