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 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建