*#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$