Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forked processes order of execution

Tags:

c

fork

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.

like image 735
Bob Avatar asked Feb 07 '23 01:02

Bob


1 Answers

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.

like image 101
Eugene Sh. Avatar answered Feb 21 '23 13:02

Eugene Sh.