简体   繁体   中英

How to make signal handler only run it once and terminate all processes?

I have N child process and a parent process. I have signal handler which in below code code.

void unlink_semaphores(){

sem_unlink(SEM_NAME1) < 0;
   // perror("sem_unlink(3) failed");

sem_unlink(SEM_NAME2) < 0;
    //perror("sem_unlink(3) failed");
sem_unlink(SEM_NAME3) < 0;
   // perror("sem_unlink(3) failed");
sem_unlink(SEM_NAME4) < 0;
   // perror("sem_unlink(3) failed");
sem_unlink(SEM_NAME5) < 0;
    //perror("sem_unlink(3) failed");
sem_unlink(SEM_NAME6) < 0;
    //perror("sem_unlink(3) failed");

sem_unlink(SEM_NAME7) < 0;
    //perror("sem_unlink(3) failed");
if (shm_unlink(SHMOBJ_PATH1) != 0) {
   // perror("In shm_unlink() of buffer 1");
    exit(1);
}
}
void sinyal_handler(int signo)

{

if (signo == SIGINT || signo == SIGTERM) {
    if(signo == SIGINT) printf("received Ctrl+C\n");
    if(signo == SIGTERM) printf("received SIGTERM \n");

    printf("closing semaphores and giving shared maps...\n");
    unlink_semaphores();
    _exit(EXIT_FAILURE);
}

}

in Main program before forking i set signal handlers.

signal(SIGINT,&sinyal_handler);
signal(SIGTERM,&sinyal_handler);

and child processes never goes outside of While(1) loop until CTRL+C comes to program and signal handler kills it with closing linked semaphores etc.

for (i = 0; i < PROCESS_N; i++) {
        if (fork() == 0) {
            // do the job specific to the child process
            //random shared variable -> ra

            while(1){ .. code->

Problem is when i press CTRL + C program calls signal handlers multiple times and print info, try to unlink files multiple times.

How to fix this?

When you fork a new process then the newly forked child will inherit the signal handlers of the parent. So in your case both the parent and the child process will have the same signal handlers and when a signal is received both of them will run.

To fix this, you can register signal handlers after fork, only in the parent process or you can block the signals in the child process by using sigprocmask

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