简体   繁体   English

如何使信号处理程序仅运行一次并终止所有进程?

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

I have N child process and a parent process. 我有N个子进程和一个父进程。 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. 并且子进程永远不会进入While(1)循环之外,直到CTRL + C进入程序并且信号处理程序通过关闭链接的信号灯等将其杀死。

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. 问题是当我按CTRL + C程序多次调用信号处理程序并打印信息时,尝试多次取消链接文件。

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 要解决此问题,您可以在fork之后仅在父进程中注册信号处理程序,也可以使用sigprocmask阻止子进程中的信号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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