简体   繁体   中英

How to send signal SIGUSR1 and SIGUSR2 from parent to children?

I have the following source code, which I am sending signals from parent to child:

sigset_t sig_m1, sig_m2, sig_null;
int signal_flag=0;

void start_signalset();

void sig_func(int signr) {
  printf("%d\n", signr, n);

  start_signalset();
}

void start_signalset() {
  if(signal(SIGUSR2, sig_func) == SIG_ERR) {
    exit(0);
  }

 if(signal(SIGUSR1, sig_func) == SIG_ERR) {
    exit(0);
  }
}

void wait_for_parents() {
    while(signal_flag == 0) {
        sigsuspend(&sig_null);
    }
}


int main(){
    int result,pt_pid;
    start_signalset();
    pt_pid=getpid(); 

    result = fork();
    if(result==-1){ 

        printf("Can't fork child\n");
        exit(-1);
    } else if (result == 0) {

            wait_for_parents();

    } else {
       kill(result,SIGUSR2);
       kill(result,SIGUSR2);
       kill(result,SIGUSR1);
       kill(result,SIGUSR2);

        signal_flag = 1;
    }    
    return 0; 
}

I see: 31, 31, 31, 30, but I was expecting to see 31, 31, 30, 31. Where I have an error? I think there is some problem with synchronization. However, I do not understand how to fix it, and I'm not sure that the problem exists.

Regards, Denis.

You are sending signals so quickly that the signal handler processing SIGUSR1 gets interrupted by the next signal and processes that first before it returns.

  • signal 2 arrives, prints
  • signal 2 arrives, prints
  • signal 1 arrives, gets interrupted before it can print because another signal 2 arrives
  • signal 2 arrives, prints
  • after last signal handler returned signal handler for SIGUSR1 continues execution and prints.

Either send your parent some sort or acknowledgement, make your parent sleep a while or make your signal handler return faster (store signal arrival in a buffer. Invoking printf is quite a long call.

When signals for a process arrive a random thread of that process gets interrupted and begins executing the signal handler. If the signal handler returns the thread will continue execution as usual. Signal handlers can also be interrupted!

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