【发布时间】:2014-03-02 10:01:37
【问题描述】:
当下面的代码运行时,我知道父子都将在调用 fork() 后立即并行运行。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
char buf[30];
pipe(pfds);
if (!fork()) {
printf(" CHILD: writing to the pipe\n");
write(pfds[1], "test", 5);
printf(" CHILD: exiting\n");
exit(0);
} else {
printf("PARENT: reading from pipe\n");
read(pfds[0], buf, 5);
printf("PARENT: read \"%s\"\n", buf);
wait(NULL);
}
return 0;
}
这意味着孩子将执行:
printf(" CHILD: writing to the pipe\n");
而父级会执行
printf("PARENT: reading from pipe\n");
并行。
对于那些不熟悉C的人,在sh:
$ sh -c 'echo CHILD & echo PARENT; wait'
PARENT
CHILD
所以我在单核 cpu 和双核 cpu 上运行此代码,但我注意到 parent 总是首先打印。由于两者是并行的,因此期望随机顺序是很合理的。但事实并非如此。为什么会这样?
【问题讨论】:
-
这个问题在这里合适还是应该移到stackoverflow?
-
这里很合适,这不是编程问题,而是关于给定 Unix/Linux 调度程序行为的问题。
-
在 Linux 3.12 上,如果我有
sudo sysctl -w kernel.sched_child_runs_first=1和其他一些,我有时可以使用sh -c 'sleep 1; echo CHILD & echo PARENT; wait'让孩子先运行(也就是说,在分叉之前让 sh 进程空闲一段时间) CPU 密集型进程同时运行。考虑到许多参数,调度算法是相当复杂的。我想说在这里抱任何期望是毫无意义的。 -
您应该重写您的问题并删除
pipe方面,因为它与此处无关以避免混淆。 -
@user25108 考虑到任何 shell 在 fork 操作之后可能是 yielding parent、child、both 或 none。
标签: fork