2010-11-24 131 views
0

我嘗試了一個來自此網站的示例:http://www.cs.cf.ac.uk/Dave/C/node24.html 有時,輸出不會顯示來自子進程的消息。 我想明白爲什麼?任何人都可以幫忙嗎?子進程無法正常工作

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

void sighup(); /* routines child will call upon sigtrap */ 
void sigint(); 
void sigquit(); 

main() 
{ int pid; 

    /* get child process */ 

    if ((pid = fork()) < 0) { 
     perror("fork"); 
     exit(1); 
    } 

    if (pid == 0) 
    { /* child */ 
     signal(SIGHUP,sighup); /* set function calls */ 
     signal(SIGINT,sigint); 
     signal(SIGQUIT, sigquit); 
     for(;;); /* loop for ever */ 
    } 
    else /* parent */ 
    { /* pid hold id of child */ 
     printf("\nPARENT: sending SIGHUP\n\n"); 
     kill(pid,SIGHUP); 
     sleep(3); /* pause for 3 secs */ 
     printf("\nPARENT: sending SIGINT\n\n"); 
     kill(pid,SIGINT); 
     sleep(3); /* pause for 3 secs */ 
     printf("\nPARENT: sending SIGQUIT\n\n"); 
     kill(pid,SIGQUIT); 
     sleep(3); 
    } 
} 

void sighup() 

{ signal(SIGHUP,sighup); /* reset signal */ 
    printf("CHILD: I have received a SIGHUP\n"); 
} 

void sigint() 

{ signal(SIGINT,sigint); /* reset signal */ 
    printf("CHILD: I have received a SIGINT\n"); 
} 

void sigquit() 

{ printf("My DADDY has Killed me!!!\n"); 
    exit(0); 
} 

回答

1

因爲有時父母會在孩子運行之前被安排,有時反之亦然。如果孩子在信號傳遞時沒有設置處理程序,則看不到您的消息。

+2

解決方案 - 在fork()之前設置信號處理程序然後在父項中取消設置 – tobyodavies 2010-11-24 02:46:58

1

孩子已經將所有他把手

if (pid == 0) 
{ /* child */ 
    signal(SIGHUP,sighup); /* set function calls */ 
    signal(SIGINT,sigint); 
    signal(SIGQUIT, sigquit); 
    kill(getppid() , SOMESIGNAL); 
    for(;;); /* loop for ever */ 
} 

,並確保父將使用暫停()

pause(); 
    printf("\nPARENT: sending SIGHUP\n\n"); 
    kill(pid,SIGHUP); 
    sleep(3); /* pause for 3 secs */  
    printf("\nPARENT: sending SIGINT\n\n"); 
    kill(pid,SIGINT); 
    sleep(3); /* pause for 3 secs */ 
    printf("\nPARENT: sending SIGQUIT\n\n"); 
    kill(pid,SIGQUIT); 
    sleep(3); 

你的處理程序等待信號後,您可以發送父的信號句柄SOMESIGNAL可以這樣實現

void sig_somesignal() 
{ 
    return; 
    }