2011-07-05 33 views
1
/* In alarm.c, the first function, ding, simulates an alarm clock. */ 

#include <signal.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <stdlib.h> 

static int alarm_fired = 0; 

void ding(int sig) 
{ 
    alarm_fired = 1; 
} 

/* In main, we tell the child process to wait for five seconds 
    before sending a SIGALRM signal to its parent. */ 

int main() 
{ 
    pid_t pid; 

    printf("alarm application starting\n"); 

    pid = fork(); 
    switch(pid) { 
    case -1: 
     /* Failure */ 
     perror("fork failed"); 
     exit(1); 
    case 0: 
     /* child */ 
     sleep(5); 
     printf("getppid: %d\n", getppid()); // Question: why this line produces the same value as getpid? 
     kill(getppid(), SIGALRM); 
     exit(0); 
    } 

/* The parent process arranges to catch SIGALRM with a call to signal 
    and then waits for the inevitable. */ 

    printf("waiting for alarm to go off\n"); 
    (void) signal(SIGALRM, ding); 

    printf("pid: %d\n", getpid()); // Question: why this line produces the same value as getppid? 
    pause(); 
    if (alarm_fired) 
     printf("Ding!\n"); 

    printf("done\n"); 
    exit(0); 
} 

我已經Ubuntu的10.04下運行上面的代碼LTS爲什麼getppid和GETPID返回相同的值

> [email protected]:~/Documents/./alarm 
> alarm application starting 
> waiting for alarm to go off 
> pid: 3055 
> getppid: 3055 
> Ding! 
> done 

回答

9

嗯,在孩子,你叫getppid它返回孩子的父母-PID內部原因。 和父母內部,請致電getpid,它返回父母(自己)的pid

從子項調用getppid(獲取父pid)與從父母調用getpid相同。

所以價值是一樣的。這是不是很直接和預期?

相關問題