elP*_*ris 1 c++ multithreading operating-system fork
今天,我用C++编写了一个小程序:
pid_t pChild=0;
printf("Main process ID:%d\n",getpid());
pChild= fork();
printf("%d\n",pChild);
if (pChild!=0){
printf("Parent process ID:%d\n",getpid());
printf("Child process ID:%d\n",pChild);
}
else printf("Sorry! The child can not be created\n");
return 0;
Run Code Online (Sandbox Code Playgroud)
输出就像这样
主进程ID:3140
抱歉! 无法创建孩子
父进程ID:3140
子进程ID:3141
然后,我想知道输出.
我猜测子进程的第一个getpid()没有运行,因为它从其父进程中使用getpid()读取相同的数据; 而这个消息
抱歉! 无法创建孩子
它必须来自子进程的if语句.如果我错了,请纠正我
但我仍然无法理解为什么孩子的fork()函数没有运行.为什么被阻止?是因为它们读取了相同的pChild数据(子进程中的fork()之一,另一个是主进程的if语句)?
任何人都可以解释更多细节吗?谢谢.