子进程无法完成,因为父进程先完成

时间:2019-01-25 01:31:18

标签: c linux process fork exec

据我了解,在fork()之后,如果父级不调用wait()并在其子级之前完成,则子级仍然应该能够继续完成他们的工作。 (因为它们被init拾取)。 但是,在我的代码中,除非父母在一定时间内等待wait()或sleep()基本上是在等待他们完成,否则孩子们无法完成他们正在做的事情。

int main(int argc, char *argv[]) {
    pid_t pid;
    int i = 0;
    while (i < 3) {
      ++i;
      switch (pid = fork()) {
        case -1: {
            printf("couldn't fork\n");
            exit(0);
        }

        case 0: {
            execv(...) // The forked child goes off to execute some other 
                       // program.
                       // The other program prints a line to console every 
                       // 2 seconds. It prints 3 lines altogether.

            perror("couldn't execv\n");
            exit(0);
        }
      }
    }
             // while should spawn 3 children and print 9 lines.
   sleep(10) // If I sleep here the 9 lines will show.
             // Or if I wait 3 times
             //int j = 0;
            // while (j < 3) {
            // ++j; wait(NULL);
             // }

// But if I don't wait or sleep, only 3 lines (the first line of each 
// childprocess is printed)
}

这是execv执行的另一个程序

#include <stdio.h>
#include <stdlib.h>


int main(int argc, char *argv[]) {
printf("a\n");
sleep(2);
printf("b\n");
sleep(2);
printf("c\n");
sleep(2);
return 0;
}

如果我不睡觉()或等待(),则输出为

a
a
a

如果我sleep()或wait(),将显示正确的输出。

a
a
a
b
b
b
c
c
c

0 个答案:

没有答案