Search code examples
unixprocessforkexecwait

If you fork() and exec() from the child process, and wait in the parent, how does the parent get a return code from the child?


I'm learning about fork(), exec(), etc. and I ran into something in a textbook that I don't fully understand.

In the example, a process calls fork().

In the child process, we call exec().

Later, in the parent, we call wait().

It is my understanding that a successful exec() call never returns. If we called exec() in the child, how can we wait for the child to return in the parent, if the child will never have control returned to it from the exec()?

My only guess here is that what happens is the parent, thinking it's waiting on the child, is actually waiting on the new process created with exec? I.e. normally I'd fork() and wait for the child. If I fork() and exec the UNIX program date then wait for the child in the parent, am I actually now waiting for date to exit?

Thanks!


Solution

  • You need to distinguish the process from the program. Calling exec runs a different program in the same process. The exec function doesn't return (except to signal an error) because it terminates the program that calls in. However, the process is reused to run a different program. In a way, from the perspective of the process running exec, the exec function returns as the entry point of the new program.

    From the point of view of the parent, there's a child process. That's all the parent knows. The parent doesn't know that the child called exec, unless it watches it and finds out by indirect means such as running ps. The parent is just waiting for the child process to exit, no matter what program the child process happens to be running.