c++ - 在 fork() 之后,我的程序中不断得到相同的 pid
问题描述
这是代码
pid_t pid;
srand(time(NULL));
for (int i=0; i < 2; i++)
{
pid = fork();
if (pid < 0)
{
std::cout<< "fork failed";
return -1;
}
else if (pid == 0)
{
std::cout<< "Process "<< i+1 << " ID: " << pid <<std::endl;
std::thread one (threadFunction, 0);
std::thread two (threadFunction, 1);
std::thread three (threadFunction, 2);
one.join();
two.join();
three.join();
}
else
{
wait (NULL);
exit(0);
}
}
该循环应该创建两个不同的进程,但每当我运行它时,输出 pid 始终为 0。这是否意味着它是同一个进程
解决方案
如果 pid == 0 您的代码正在执行子进程。如果 pid 不同于 0,您的代码将执行父进程
请参阅 man http://man7.org/linux/man-pages/man2/fork.2.html的部分返回值
您可以使用函数 getpid 找出孩子的真实 pid
推荐阅读
- python - 康托尔集代码没有给出预期的输出
- android - 使用 Ionic 4 和 Capacitor 构建时创建的 APK 文件在哪里?
- javascript - Gulp:错误:未处理的“错误”事件。(1)当phpunit测试失败时
- python - 如何使用 Amplify React 在 Python 中的 Post Confirmation Lambda Trigger 中获取 Cognito Identity Id?
- reactjs - React async / await 不在调用函数中等待 - 但被调用函数正在正确执行
- java - Java 多播:如何在 localhost 上进行测试?
- swift - 在 Vapor 3 中返回部分对象
- android - 将android java项目转换为android kotlin项目
- javascript - 两个类似的 SQLite 案例语句,一个有效,另一个无效
- bash - 为什么这个 docker shell 命令不起作用