[英]I keep getting the same pid in my program after fork()
This is the code这是代码
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);
}
}
The loop is supposed to create two different processes but whenever I run this the output pid is always 0. Does this mean it the same process该循环应该创建两个不同的进程,但是每当我运行它时,输出 pid 始终为 0。这是否意味着它是相同的进程
if pid == 0 your code is executing the child process.如果 pid == 0 您的代码正在执行子进程。 If pid is different than 0 your code execute the parent process
如果 pid 不同于 0 您的代码执行父进程
see section return value of the man http://man7.org/linux/man-pages/man2/fork.2.html参见 man http://man7.org/linux/man-pages/man2/fork.2.html 的部分返回值
you can find out the real pid of the child with function getpid你可以用函数getpid找出孩子的真实pid
http://man7.org/linux/man-pages/man2/getpid.2.html http://man7.org/linux/man-pages/man2/getpid.2.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.