以最简单的形式使用 fork() 需要按回车键才能完成执行

Using fork() in simplest form need to hit enter to finish execution

我想运行一些简单的例子来了解fork()系统调用是如何工作的。

它的工作,但需要在打印后按回车键退出程序 child process

#include <stdio.h>
#include <unistd.h> 

int main()
{
    pid_t pid;
    pid = fork();

    if(pid == 0){
        printf("child process\n");
    }
    else{
        printf("parent process\n");
    }
    return 0;
}

编译,运行&输出

ss@ss:~$ gcc dd.c -o dd
ss@ss:~$ ./dd
parent process
ss@ss:~$ child process

在屏幕程序上打印子进程后需要按回车键 return 到终端。

终端等待输入新命令,如果刚按回车return,写入 ss@ss: 还行。

或者我们可以输入任何其他终端命令 并执行。

我想知道为什么会出现这种情况,如果程序真的在打印后完成了 child process 为什么终端不显示 ss@ss:~$

这是我的机器信息

gcc --version

gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

uname -a

Linux ss 4.8.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb 5 09:39:41 UTC 2017 i686 i686 i686 GNU/Linux

编辑

除了Felix Guo通过在printf("Parent process")之后添加wait(NULL)来回答,强制父进程等待子进程。

我找到另一种方法 from 通过在终端中使用 > 运算符将程序输出重定向到任意文件。

在执行命令中:

./dd > out.txt

它将输出重定向到 out.txt 文件。 如果我们 cat 这个文件:

$cat out.txt
parent process
child process

这是使用 fork().

查看程序正确输出的另一种方法

[编辑 2]

#include <stdio.h>
#include <unistd.h> 
#include <sys/wait.h>

int main()
{
    pid_t pid;
    pid = fork();

    if(pid == 0){
        printf("child process: \n\t");
        printf("PID: %d\n\tPPID: %d\n", getpid(), getppid());
    }
    else{
        printf("parent process: \n\t");
        printf("PID: %d\n\tPPID: %d\n", getpid(), getppid());
        wait(NULL);
    }

    return 0;
}

输出

parent process: 
    PID: 4344
    PPID: 4336    < --- OS
child process: 
    PID: 4345
    PPID: 4344    < --- parent process

您的 parent 进程在等待您的 child 进程完成之前退出,因此 parent 进程将完成,这是终端正在等待的,因此终端将return到它的命令输入状态,从而输出ss@ss...。然后你的 child 处理打印并刷新 stdout 到屏幕,然后输出 child process 到终端,但是由于终端已经输出了提示 ss@ss,它结束了提示。

解决方法是在parent进程中return 0之前等待child进程退出。您可以在 printf("Parent process") 之后使用 wait(NULL) 来等待 child 过程,如下所述:Make parent wait for all child processes

它可能看起来不像,但终端已准备好在父进程完成后立即接受新命令。

发生的事情是 shell 正在打印提示,然后子进程(与 shell 同时 运行ning)输出一个字符串。如果您要输入另一个命令而没有先按回车键来查看另一个提示,您将看到该命令将 运行.

例如:

[dbush@dbush ~]$ ./x1
parent process
[dbush@dbush ~]$ child process
echo hello
hello
[dbush@dbush ~]$ 

这里,我输入echo hello,光标在最左边,命令是运行。