我正在尝试运行这段 hello world 代码:
#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);
}
}
关于 child 的父 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。请任何人解释这些结果。
最佳答案
你有竞争条件。有时,您的 parent 完成得更快一些,当您看到这种奇怪的结果(不同的 parent ID)时就是这种情况。
在 parent 里面睡一会儿,看看会发生什么。
其实可以等你的 child :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);
...
关于c - getpid() 返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846901/