fork() execution in for loop

后端 未结 3 1714
谎友^
谎友^ 2021-01-24 23:27
int main(int argc, char** argv) {
    int i = 0;
    while (i < 2) {
        fork();
        system(\"ps -o pid,ppid,comm,stat\");
        i++;
     }
     return (EX         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 00:08

    I believe the answer is 6.

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

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

    total calls to ps: 2+4=6.

提交回复
热议问题