Bob
Bob

Reputation: 735

Forked processes order of execution

I know there's another thread with the same name, but this is actually a different question.

When a process forks multiple times, does the parent finish executing before the children? Vice versa? Concurrently?

Here's an example. Lets say I have a for loop that forks 1 parent process into 4 children. At the end of that for loop, I want the parent process to feed some data to the children via pipes. The data is written to each child process' respective stdin.

Will the parent send the data first, before any of the children execute their code? This is important, because we don't want it to start working from an invalid stdin.

Upvotes: 4

Views: 1297

Answers (3)

Dilip Kumar
Dilip Kumar

Reputation: 1746

When a process forks multiple times, does the parent finish executing before the children? Vice versa? Concurrently? -

Concurrently and depends on the scheduler and its unpredictable.

Using pipe to pass integer values between parent and child

This link explains in detail about sharing data between parent process and child. Since you have four child process you may need to create different individual pipes between each child process.

Each byte of data written to a pipe will be read exactly once. It isn't duplicated to every process with the read end of the pipe open.

Multiple child processes reading/writing on the same pipe

Alternatively you can try shared memory for the data transfer.

Upvotes: 1

Eugene Sh.
Eugene Sh.

Reputation: 18299

The order of the execution is determined by the specific OS scheduling policy and not guaranteed by anything. In order to synchronize the processes there are special facilities for the inter-process communication (IPC) which are designed for this purpose. The mentioned pipes are one example. They make the reading process to actually wait for the other process to write it, creating a (one-way) synchronization point. The other examples would be FIFOs and sockets. For simpler tasks the wait() family of functions or signals can be used.

Upvotes: 7

Daniel Paczuski Bak
Daniel Paczuski Bak

Reputation: 4080

They will execute concurrently. This is basically the point of processes.

Look into mutexes or other ways to deal with concurrency.

Upvotes: 0

Related Questions