2015-10-14 156 views
0

我嘗試檢查父進程和子進程的PID,但每當我運行該程序時,我所得到的都是它們兩者的相同PID值。爲什麼子進程和父進程的pid相同?

從我所知的getpid獲取當前進程的pid。我錯了嗎? same valur of pid for both processes

#include <sys/types.h> 
    #include <stdio.h> 
    #include <unistd.h> 


    int main (void){ 

pid_t pid= fork(); 
switch (pid){ 
case -1: 
    perror("fork"); 
    exit(1); 
     break; 
case 0 : 
    printf("Child Process - my pid: %d, my parent's pid: %d\n", (int)getpid, (int)getppid); 
    break; 
default : 
    wait(); 
    printf("parent process - my pid: %d, my parent's pid: %d, my child's pid: %d\n", (int)getpid, (int)getppid, (int)pid); 
    break;} 


    printf("End of fork\n"); 
    return 0; 
    } 

回答

1

您還沒有叫getpidgetppid功能,你只將它們轉換成整數。你需要添加括號。

printf("parent process - my pid: %d, my parent's pid: %d, my child's pid: %d\n", getpid(), getppid(), pid); 

請注意,打印的錯誤值遠遠超出PID範圍,即typically 32k。您的父進程正在打印正確的子PID,因爲該值在交給您時是整數。