【发布时间】:2019-04-26 08:20:23
【问题描述】:
假设check_if_pid_exists(pid) 在存在具有这种 pid 的进程时返回 true(但可能尚未运行),或者在没有具有这种 pid 的进程时返回 false >,当fork() 返回子pid 时,父代码中是否有机会出现竞争条件,但是内核没有机会初始化数据结构以便check_if_pid_exists(child) 返回错误的?或者也许在从fork() 返回之后,我们可以保证check_if_pid_exists(pid) 返回 true?
pid_t child = fork();
if (child == 0) {
/* here the child just busy waits */
for (;;)
;
}
if (child > 0) {
/* here the parent checks whether child PID already exists */
check_if_pid_exists(child);
}
【问题讨论】:
-
如果外部事件真的很快杀死了孩子(例如 systemtap 脚本监控分叉),
check_if_pid_exists(child)可能会返回 false。 -
正确,谢谢。但是假设没有“第三方”代理杀死我们的进程?
-
它可能被第一方杀死,比如资源限制
-
我认为,由于内核旨在适应父级在 fork 调用
wait系统调用后发出的前两条指令的情况,因此内核几乎可以肯定到那时已经完全设置了子级分叉返回。
标签: c linux linux-kernel operating-system