[英]getpid() returns unexpected value
我正在嘗試運行這段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);
}
}
每次關於孩子的父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);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.