I know that it can be either of these. But I always see that the child executes first on my UNIX terminal. Also, why don't the parent and child execute in parallel. They seem to be executing serially. Is this because they share the same terminal?
Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.
A process goes through different states before it gets terminated. The first state that any process goes through is the creation of itself. Process creation happens through the use of fork() system call, which creates a new process(child process) by duplicating an existing one(parent process).
RETURN VALUE Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
The fork starts from line 3, the point where the fork occurred.
In general, nothing can be said about the relative order of their execution.
Now, let's consider your specific problem. If:
Most likely this indicates that there is some (perhaps unintended) synchronization going on between the two processes.
Actually that is the intended behavior, even if it is not currently functioning as it should, meaning that the parent can run before the child and the child can run before the parent.
The goal is to run the child process first.
In short, the logic behind it is that if the child is ran first, the overhead of copy on write (COW) is eliminated if the child is calling exec
since the parent does not have any chance to write to the address space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With