fork() execution in for loop

后端 未结 3 1760
谎友^
谎友^ 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:14

    6 times.

    It creates a process tree like this:

    A-+
      |-B-+
      |   |-C-+
      |-D
    

    A does it twice (i=0)

    B does it twice (i=0)

    C does it once (i=1)

    D does it once (i=1)

    Note that my usage of letters is to distinguish them. There's no predictable output ordering since process switching is non-deterministic to the eyes of a programmer.

提交回复
热议问题