Дочерние процессы не могут завершиться, потому что родительский закончил первым - PullRequest
0 голосов
/ 25 января 2019

Из того, что я понимаю, после 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

Если я сплю () или жду (), отображается правильный вывод.

a
a
a
b
b
b
c
c
c
...