GETPID()返回意外值
问题描述:
我试图运行这块的Hello World代码:GETPID()返回意外值
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
char string1[] = "\n Hello";
char string2[] = " World.\n";
int main(void)
{
int childpid;
if((childpid = fork()) == -1){
printf("\n Can't fork.\n");
exit(0);
}
else if(childpid == 0){ /* Child process */
printf("\n Child: My pid = %d, Parent pid = %d \n", getpid(), getppid());
exit(0);
}
else{ /* Parent Process */
printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid());
exit(0);
}
}
对于孩子的父母PID每次我得到的输出是不同的:
~$ ./f
Parent: Child pid = 6394, My pid = 6393, Parent pid = 27383
Child: My pid = 6394, Parent pid = 1842
~$ ./f
Parent: Child pid = 6398, My pid = 6397, Parent pid = 27383
Child: My pid = 6398, Parent pid = 6397
当我检查到pid = 1842
属于哪个进程时,我发现它是/sbin/upstart --user
的pid。任何人都请解释这些结果。
答
您有竞赛状况。有时候,你的父母会更快一点,当你看到这个奇怪的结果(不同的父母ID)时,就是这种情况。
在家长里面睡了一会儿,看看会发生什么。
事实上,你可以等待你的孩子:waitpid函数
...
int status;
waitpid(childpid, &status, 0);
printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid());
exit(0);
...
我无法重现您的问题。您粘贴的代码显示我的机器上的预期行为 –