C getpid()返回意外值
我正在尝试运行这段hello world代码:C getpid()返回意外值,c,fork,C,Fork,我正在尝试运行这段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() ) =
#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=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);
...
你有比赛条件。有时候,你的父母完成得快一点,当你看到这个奇怪的结果(不同的父母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);
...
我无法重现你的问题。您粘贴的代码显示了我的机器上的预期行为我无法重现您的问题。您粘贴的代码显示了我的计算机上的预期行为