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?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
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.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.
There is not really one executing before the other. It is simply that the parent will
fork()
thenwait()
for the child to complete. It may even fork several times if you use a piped series of commands for instance.If you are calling vfork then almost all implementations define that the child will run first and then parent will execute.(Untill child calls exec).So you will notice serial execution in case of vfork irrespective of schedular.However when a fork is called simply two new processes are created.They are free to run independently.(Just like any other process). Which process runs first will be heavily dependent on the scheduling algorithm. Beside scheduling algorithm the number of processes running at that time will also determine the nature of output.Moreover if you are using standard library i/o functions they output data in bursts(probably not the right word). That will also determine to some extent who gets to write first. Here is a sample code(That doesn't make much sense practically but still a good example that parent and child indeed run in synchronism
For my system the following output comes
However if reduce the number of forks to two(Only two processes competing) then the output is less ugly.Its the parent which executes first.(Probably because its current running process when the other process is created)