fork()之后的PID是多少?
我正在 C 程序中连续执行 3 个 fork。
1. 是否会按照相同的顺序执行? (我的猜测是肯定的)。
2. 如果我从 shell 执行 pgrep myexecutable
,它会按照启动时的顺序给出进程 ID 吗? (我的猜测是否定的,因为你不能保证系统给孩子的pid是什么,对吧?)
I am doing 3 consecutive forks in a C program.
1. Is it going to execute in the same order ? ( My guess is yes ).
2. If I do a pgrep myexecutable
from shell, would it give the process ids in the same order as they were started ? ( my guess is no, because you cant guarantee what pid the system gives the child, right ? )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行 3 个 fork 后,总共将运行 8 个进程
所以现在 pid 将取决于子进程的创建顺序以及子进程的子进程的创建顺序。
可能就像
There would be a total of 8 processes running after 3 forks are executed
so now the pid would be depend on which order the child process are created by and also in which order the children of children are created.
could be like
Shrinath,您应该检查 fork() 的文档,如下:
对您来说,这意味着您的父进程在分叉时将获得子进程的 PID。子进程知道它是子进程,因为
fork()
会将 0 返回给子进程,因此类似于:当心您得到负数的机会(因此没有子进程),您应该检查那。
ps 的输出会因系统而异,但如果您查看整个树,您应该会看到一个示例(让您的进程休眠,以便您有时间检查 ps) > 输出。)
Shrinath, you should check the documentation for
fork()
, here it is:All that means for you, is that means your parent process will get the child's PID when it forks. The child knows it's the child, because
fork()
will return 0 to the child, so something like:Beware for the chance that you get a minus number (so there's no child), you should check for that.
The output of
ps
will vary by system, but you should see an example, if you look at the whole tree (make your processes sleep, so you have time to check theps
output.)