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
SIGUSR1gets interrupted by the next signal and processes that first before it returns.SIGUSR1continues 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
printfis 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!