使用 fork 创建多个进程 [英] Creating more than one process using fork

查看:79
本文介绍了使用 fork 创建多个进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在与我的朋友激烈讨论后,我们决定问问我们的直觉是否在正确的道路上.问题出在 fork() 函数或子进程上.代码如下:

After a strong discusion with my friend, we decided to ask if our intuition is on the right path. The problem is with the fork() function or rather with the child processes. Here's the code:

int main()
{
    int status;
    if(!fork()) execl("pp1",NULL);
    if(!fork()) execl("pp2",NULL);
    if(!fork()) execl("pp3",NULL);
    wait(&status);
    return status;
}

作者解释说这个程序将只创建3个子进程,但是当遇到第一个子进程时,它会进入第一个if"并作为一个新进程执行pp1,但与子进程具有相同的pid,没关系.问题在于第二个和第三个孩子,它将如何运行此代码.我们的直觉是我们不会遇到第二个和第三个如果".程序 pp1 将由所有 3 个子进程运行 3 次.

The author explains that this program is going to create only 3 child processes, but when it come to the first child, it will enter the first "if" and execute pp1 as a new process but with the same pid as child, and that's ok. The problem is with the second and third child, how it will run this code. Our intuision is that we won't get to the second and third "if". Program pp1 will be run 3 times by all of the 3 children processes.

你怎么看?结果会怎样?

What do you think? What will be the result?

推荐答案

注意 fork() 的返回值.来自man 2 fork:

Note the return values of fork(). From man 2 fork:

成功时,父进程返回子进程的PID,子进程返回0.失败时,在父进程中返回 -1,不创建子进程,并适当设置 errno每天.

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropri‐ ately.

表示子进程在成功fork后收到0.当 !0 的计算结果为 true 时,子进程执行 execl,而父进程前进到下一个 fork()>.

Meaning the child process receives 0 after successful fork. As !0 evaluates to true the child execute execl then, while the father steps forward to the next fork().

这篇关于使用 fork 创建多个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆