为什么我的控制台看起来像是在使用 fork() 创建 3 children 后执行了命令?

why does my console look like it performed a command after using fork() to create 3 children?

好的,所以要么我这边有这个奇怪的错误,要么它只是我这边的一个错误,我不需要担心。无论如何,我正在做一个作业,我需要 fork 3 次,我这里有一些快速的虚拟代码:

for(int x = 0; x < 3; x++) {
    procID = fork();
    if (procID == 0) {
        sleep(3);
        printf("child process: \n");
        exit(0);
    }

}

这是输出 i want/need:

y@y:~/Desktop/playground$ ./a
child process
child process
child process
y@y:~/Desktop/playground$

但这是我得到的输出:

y@y:~/Desktop/playground$ gcc a.c -o a -lm
y@y:~/Desktop/playground$ ./a
y@y:~/Desktop/playground$ child process
child process
child process

包含问题的行是这一行:y@y:~/Desktop/playground$ child process

为什么它自动使它看起来好像我在控制台中输入了命令 y@y:~/Desktop/playground$ child 进程。我正在深入研究它并试图自己解决这个问题,但显然我不能自己做。我知道一旦最后一个 parent 退出然后“y@y:~/Desktop/playground$”被放入控制台,我能做些什么来强制 parent 等到children执行完了吗?还是这里有其他事情在起作用?

why does it automatically make it look as if i input the command [..]

没有。您看到的是 shell 提示符。

原因是您没有从 parent 进程中调用 wait(2) 让所有 child 进程退出。因此,当 parent 在一个或多个 children 之前退出时,您会观察到这种行为。

is there anything i can do to force the parent to wait until the children have finished executing?

在for循环之后的循环中调用wait(NULL);,这样parent等待所有children:

while (wait(NULL) > 0);

所以 wait(NULL) 确实是我需要做的。如果您遇到同样的问题,您需要等待(NULL);对于与您拥有的 children 相同的数量。