简体   繁体   中英

C program - Process don't invoke after sending SIGTERM signal

I am new in using signals on C programming.

I wrote two simple source codes child.c and parent.c in order to demonstrate my issue.

child.c

void errorHandler(char* message);
void sigterm_handler(int signum, siginfo_t* info, void* ptr);

int main(){

    struct sigaction action1;
    memset(&action1, 0, sizeof(action1));
    action1.sa_sigaction = sigterm_handler;
    action1.sa_flags = SA_SIGINFO;

    if(sigaction(SIGTERM, &action1, NULL) != 0)
        errorHandler("Signal sigterm_handler registration failed");

    for(int i = 0; i < 10; i++){

        printf("%d\n", i);
        if(i == 5){

            if(raise(SIGSTOP)!= 0)
                errorHandler("Raise SIGSTOP failed");
        }
    }

    return EXIT_SUCCESS;
}

void errorHandler(char* message){

    printf("Error: %s: %s\n", message, strerror(errno));
    exit(EXIT_FAILURE);
}

void sigterm_handler(int signum, siginfo_t* info, void* ptr){

    printf("Child: Process %d finishes\n", getpid());
    exit(EXIT_SUCCESS);
}

parent.c

int main(int argc, char* argv[]){

    int status;
    pid_t mem;
    pid_t child = fork();

    if(child == 0){

        char* arr[] = {"./child", NULL};
        execv(arr[0], arr);
    }

    else if(child > 0){

        mem = child;
        waitpid(mem, &status, WUNTRACED);
    }

    if(WSTOPSIG(status)){

        printf("Sending SIGTERM to child\n");
        kill(mem, SIGTERM);
        waitpid(mem, &status, 0);
    }

    return 0;
}

When I run parent.c, the program print into stdout:

1
2
3
4
5
Sending SIGTERM to child

but then the program get stuck, probably because sigterm_handler don't invoke, instead of printing "Child: Process *** finishes".

I tried to read on the linux manual page but I still can't to figure it out.

Can anyone please explain to me what is causing this issue?

Any answer would be appreciated!

The problem is, that the child process, that calls

if(raise(SIGSTOP) != 0)

is still stopped , when the parent here

kill(mem, SIGTERM);

sends the signal SIGTERM . The signal is not lost, but is still pending at the child's process and will be delivered, as soon as the process continues to run. You can achieve that by issuing

kill(mem, SIGCONT);

directly after sending the SIGTERM . Then, the child will resume to run, the signal will be delivered and the handler will be executed, printing the diagnostic message and exiting the process.

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