Lucien_zhou 2017-03-19 06:17 采纳率: 0%
浏览 2056

在Linux系统下使用fork() 函数,提示符会在子进程之前运行的原因?

*#include
#include

int main()
{
pid_t fpid;
int count = 0;

fpid = fork();

if (fpid > 0) {
    printf("I am the parent process, my process id is %d\n",getpid());
    count++;
    printf("parent process's count is %d\n\n",count);

// sleep(5);
}
else if (fpid == 0){
printf("I am the child process, my process id is %d\n",getpid());
count++;
printf("child process's count is %d\n\n",count);
}
else {
printf("error\n");
}

printf("the last count is %d\n",count);
return 0;

}


运行后的结果如下图所示:

图片说明

正如上面的截图所示,在运行完父进程后,会出现Linux下的shell 命令提示行后再执行子进程,请教下这是为什么的?

注意:我明白fork函数是一次调用二次返回,我想问的是:为什么不是父进程执行完,子进程执行完后,再出现 shell 命令提示行。我关心的是那个shell提示行在父子进程执行过程中什么时候会被执行??

zhouci@ubuntu:/mnt/hgfs/Ubuntu-Windows$ ./fork
I am the parent process, my process id is 3425
parent process's count is 1

the last count is 1
I am the child process, my process id is 3426
child process's count is 1

the last count is 1

zhouci@ubuntu:/mnt/hgfs/Ubuntu-Windows$

  • 写回答

1条回答 默认 最新

  • oyljerry 2017-03-19 07:25
    关注

    因为父进程是当前shell命令执行的,它结束了,就返回了shell。后面是子进程继续打印信息。

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog