Ubuntu 上的 PID 是如何生成的?
我刚刚编写了一个分叉一个进程的程序。子进程仅显示“HI”200 次。父亲进程只是说他是父亲。 我已经打印出了两个pid。 当我多次运行程序时,我发现父进程的 pid 保持不变,这是正常的。我不明白的是为什么孩子的pid不断增加2,而且正好是2。 我的问题:这是Ubuntu中pid生成的标准方法吗?增加2?
I've just wrote a program that forks one process. The child process just displays "HI" 200 times. The father process just says he's the father.
I've printed out both pids.
When I run my program multiple times, I see that the parent's pid stays the same, which is normal. What I don't understand is why the child's pid keeps getting incremented by 2, and exactly 2.
My question: Is this the standard method of pid generation in Ubuntu? Incrementing by 2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Linux 2.6 中的 PID 恰好是单调递增的,但是为什么你获得的 PID 很重要呢?不要依赖任何特定的行为。如果跳过+2,可能只是因为另一个进程恰好生成了一个子进程。或者因为 +1 会到达已在使用的 PID。
PIDs happen to be handed out monotonically increasing in Linux 2.6, but why does it matter which you get? Don't rely on any specific behavior. If there is a skip of +2 it might simply be because another process happened to spawn a child. Or because +1 would have reached a PID that is already in use.
这里找到了一个参考,说 vfork() 消耗 pid 作为副产品其运作。同样,在某些情况下,如果您从 shell 脚本分叉,则分叉可能会在实际脚本参与之前生成一个新的 shell,这也会消耗 pid。
我建议在几个 fork 之间暂停你的程序,看看是否有另一个进程占用了那些“丢失”的 pid。
Found a reference here saying that vfork() consumes a pid as a byproduct of its operation. As well, in some cases, if you're forking from a shell script, the fork might spawn a new shell before your actual script gets involved, which would also consume a pid.
I'd suggest suspending your program between a couple forks, and see if there's another process occupying those "missing" pids.