Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用fork()的程序的终端输出不正确_C_Linux_Terminal_Fork - Fatal编程技术网

C 使用fork()的程序的终端输出不正确

C 使用fork()的程序的终端输出不正确,c,linux,terminal,fork,C,Linux,Terminal,Fork,当我尝试在我的终端上运行此代码时,我会在提示符后得到输出“hello from X process”: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> void forkexample() { pid_t pidTo; int status = 0; int x = 1; if (fork() =

当我尝试在我的终端上运行此代码时,我会在提示符后得到输出“hello from X process”:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

void forkexample() 
{
    pid_t pidTo;
    int status = 0;
    int x = 1;

    if (fork() == 0){
        printf("hello from child process %d\n",getpid());
    }
    else{
        printf("hello from the parent process %d\n",getpid());
    }
}
int main()
{
    forkexample();
    exit(0);
}
#包括
#包括
#包括
#包括
void forkexample()
{
皮杜;
int status=0;
int x=1;
如果(fork()==0){
printf(“来自子进程%d的hello\n”,getpid());
}
否则{
printf(“来自父进程%d的hello\n”,getpid());
}
}
int main()
{
forkexample();
出口(0);
}
我的问题是,为什么在提示之后会出现“hello from child process”

问题 父进程不会等待子进程完成其执行

基本上,您的程序会退出&当您的子进程尚未完成打印时,shell会打印提示,因此您会在提示后从子进程获得输出

解决方案 使用:


您可以将
int
指针传递到
wait()
,它将用于存储子进程的退出状态。

我猜这与父进程正在退出,而不是等待子进程执行它需要的操作有关。子进程向标准输出启动IO序列,而父进程决定退出。Shell看到前台进程已经退出,所以它输出PS1,然后来自子进程的IO完成,然后输出。1。从shell运行程序;2.它分叉了。3.父进程执行其printf;4.父进程退出;5.shell打印带有路径的提示(因为前台进程已完成);6.子进程运行并打印其消息。
if (fork() == 0)
  {
    printf("hello from child process %d\n", getpid());
  }
else
  {
    wait(&status); // Wait for the child process
    printf("hello from the parent process %d\n", getpid());
  }