for循环中的fork()执行 [英] fork() execution in for loop

查看:473
本文介绍了for循环中的fork()执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(int argc, char** argv) {
    int i = 0;
    while (i < 2) {
        fork();
        system("ps -o pid,ppid,comm,stat");
        i++;
     }
     return (EXIT_SUCCESS);
}

有人能告诉我ps命令执行了多少次并给出解释吗?

Can anyone tell me how many times ps command is executed with an explanation?

推荐答案

我相信答案是6.

在第一次迭代中,调用了fork(),将进程分为2个,因此两次调用了ps.

in the first iteration, fork() is called, splitting the process in 2, thus calling ps twice.

在第二次迭代中,在每个进程中再次调用fork,因此您现在有4个运行ps的进程.

in the second iteration, fork is called again in each process, so you now have 4 processes running ps.

对ps的总通话次数:2 + 4 = 6.

total calls to ps: 2+4=6.

这篇关于for循环中的fork()执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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