C++ fork()、多线程和操作系统的概念

标签 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;

输出是这样的

Main process ID: 3140

Sorry! The child can not be created

Parent process ID:3140

Child process ID:3141

然后,我想知道输出结果。

我猜子进程的第一个 getpid() 没有运行,因为它从它的父进程读取了与 getpid() 相同的数据;和这条消息

Sorry! The child can not be created

必须来自子进程的if语句。如果我错了请纠正我...

但是我还是不明白为什么 child 的fork()函数没有运行。为什么被屏蔽了?是不是因为他们读取了相同的 pChild 数据(一个是子进程中的 fork(),另一个是主进程的 if 语句)?

谁能详细解释一下?谢谢。

最佳答案

来自fork() documentation :

RETURN VALUE

Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process.

您的代码假定任何 返回值都是错误。

继续:

Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.

-1 返回值是一个错误指示。

关于C++ fork()、多线程和操作系统的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516129/

相关文章:

c++ - 具有非 POD 对象的 GLib 异步队列

c - 确保不会丢失 cond 信号的安全方法

python - os.rename() 文件到文件夹名称的一部分

c - 线程_创建() : member of which C library

c++ - Oracle最新OCI版本

c++ - 在嵌套类中使用 struct vector 的成员

c++ - 索引和替换的计算成本

c++ - VC++ 中的光纤安全优化到底是什么?

c# - HttpContext.Current 如何在多线程环境中工作?

operating-system - 读取 k 字节 block 的时间(以毫秒为单位)