Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who executes first after fork(): parent or the child?

Tags:

c

fork

unix

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?

like image 376
Bruce Avatar asked Dec 13 '11 19:12

Bruce


People also ask

Which process runs first after fork?

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.

Which is the first state when the parent process executes 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).

What does fork () function returns to the parent?

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.

Where does fork start execution?

The fork starts from line 3, the point where the fork occurred.


2 Answers

In general, nothing can be said about the relative order of their execution.

Now, let's consider your specific problem. If:

  1. both processes take a non-trivial amount of time to run, and
  2. you're saying that one runs to completion before the other makes any progress, and
  3. there are unused CPU cycles, and
  4. this happens every time you run the application.

Most likely this indicates that there is some (perhaps unintended) synchronization going on between the two processes.

like image 64
NPE Avatar answered Oct 02 '22 08:10

NPE


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.

like image 34
Milan Avatar answered Oct 02 '22 06:10

Milan