在 fork() 之后,我在我的程序中不断得到相同的 pid

I keep getting the same pid in my program after fork()

本文关键字:pid 程序 fork 之后 我的      更新时间:2023-10-16

这是代码

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,则代码执行父进程

请参阅该人的返回值部分 http://man7.org/linux/man-pages/man2/fork.2.html

你可以用函数getpid找出孩子的真实PID

http://man7.org/linux/man-pages/man2/getpid.2.html