简体   繁体   中英

Sending signal from child to parent

Here I want to send SIGINT signal to parent while it is sleeping. I have tried it by writing following the program. In this program, I am not getting why the signal handler for SIGINT from the parent is not executing at all? here is the code:

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
void sig_usr(int signo){
    if(signo == SIGINT)
    printf("Signal caught!");
    return;
}

int main(void){
    pid_t pid, ppid;
    ppid = getpid();
    printf("ppid = %d\n", ppid);
    if((pid = fork()) == 0){ 
        printf("killing parent...\n");
        kill(ppid, SIGINT);
        printf("After killing parent...\n");
    }
    else{
        sleep(5);
        printf("%d %d ",ppid, pid);
        if(signal(SIGINT,sig_usr) == SIG_ERR)
            printf("Signal processed ");
    }
    return 0;
}

Output: The output is printing only this much content. I think parent is not executing at all.

输出只打印这么多内容。我认为父母根本没有执行。

You need to set the signal handler before SIGINT is sent to the parent process, otherwise, the handler will not be executed. Also, the parent process is being killed before it executes anything. The easy way to fix this would be to move the sleep call after the code for the parent process, and add a delay to the child process.

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
void sig_usr(int signo){
    if(signo == SIGINT)
    printf("Signal caught!");
    return;
}

int main(void){
    pid_t pid, ppid;
    ppid = getpid();
    printf("ppid = %d\n", ppid);
    if((pid = fork()) == 0){ 
        sleep(1); // Wait for parent to finish setting up
        printf("killing parent...\n");
        kill(ppid, SIGINT);
        printf("After killing parent...\n");
    }
    else{
        printf("%d %d ",ppid, pid);
        if(signal(SIGINT,sig_usr) == SIG_ERR)
            printf("Signal processed ");
        sleep(5); // Wait to be killed
    }
    return 0;
}

When you send SIGINT signal has not been called yet.

I think you want to set signal handler before sending SIGINT:

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
void sig_usr(int signo){
    if(signo == SIGINT)
    printf("Signal caught!");
    return;
}

int main(void){
    pid_t pid, ppid;
    ppid = getpid();
    printf("ppid = %d\n", ppid);
    if((pid = fork()) == 0){ 
        sleep(1);
        printf("killing parent...\n");
        kill(ppid, SIGINT);
        printf("After killing parent...\n");
    }
    else{
        printf("%d %d ",ppid, pid);
        if(signal(SIGINT,sig_usr) == SIG_ERR)
            printf("Signal processed ");
        sleep(5);
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM