-->

Does the Linux scheduler prefer to run child proce

2020-08-27 05:16发布

问题:

Does the Linux scheduler prefer to run the child process after fork() to the father process?

Usually, the forked process will execute exec of some kind so, it is better to let child process to run before father process(to prevent copy on write).

I assume that the child will execute exec as first operation after it will be created.

Is my assumption (that the scheduler will prefer child process) correct. If not, why? If yes, is there more reasons to run child first?

回答1:

To quote The Linux Programming Interface (pg. 525) for a general answer:

After a fork(), it is indeterminate which process - the parent or the child - next has access to the CPU. (On a multiprocessor system, they may both simultaneously get access to a CPU.)

The book goes on about the differences in kernel versions and also mentions CFS / Linux 2.6.32:

[...] since Linux 2.6.32, it is once more the parent that is, by default, run first after a fork(). This default can be changed by assigning a nonzero value to the Linux-specific /proc/sys/kernel/sched_child_runs_first file.

This behaviour is still present with CFS although there are some concerns for the future of this feature. Looking at the CFS implementation, it seems to schedule the parent before the child.

The way to go for you would be to set /proc/sys/kernel/sched_child_runs_first to a non-zero value.

Edit: This answer analyzes the default behaviour and compares it to sched_child_runs_first.



回答2:

For the case where the child calls exec at the first opportunity you can use vfork instead of fork. vfork suspends the parent until the child calls _exit or exec*. However, once it calls exec the child will be suspended if code has to be loaded from disk. In this case, the parent has a good chance to continue before the child does.