Reputation: 75
We have an assignment to explain this text of code. My only problem is understanding the handle_signal function, why did we use 2 new sigaction and then used "old_treatment" with "rien"?
#define DELAY 1
#define NB_ITERATIONS 60
void handle_signal (int num_signal){
struct sigaction rien, old_ treatment;
printf ("Signal %d => ", num_signal);
printf ("I have received a SIGTSTP.\n");
rien.sa_handler = SIG_DFL;
rien.sa_flags = 0;
sigemptyset (&rien.sa_mask);
sigaction (SIGTSTP, &rien, &old_ treatment);
printf ("Then I sleep....\n");
kill (getpid(), SIGSTOP);
printf ("They wakes me?\n");
Sigaction (SIGTSTP, &old_ treatment, NULL);
printf ("Here we go again!\n");
}
int main (void){
struct sigaction a;
int i;
a.sa_handler = handle_signal;
sigemptyset (&a.sa_mask);
sigaction (SIGTSTP, &a, NULL);
for (i = 1; i < NB_ITERATIONS; i++) {
sleep (DELAY);
printf ("%d", i % 10);
fflush (stdout);}
printf ("End\n");
return EXIT_SUCCESS;
}
Upvotes: 0
Views: 1802
Reputation: 782315
The purpose of this is to temporarily change the action for SIGTSTP
, then restore it back.
sigaction(SIGTSTP, &rien, &old_handler);
sets it to the default action, and saves the previous action in old_handler
.
Then it sends itself a SIGSTOP
signal to actually suspend the process.
When that returns, it means that the process has been continued, so it puts back the old action with:
sigaction(SIGTSTOP, &old_handler, NULL);
It's not clear why this is needed, though. It would make more sense if it suspended the process by sending a SIGTSTP
signal rather than SIGSTOP
. In that case, it needs to set the default action, otherwise it would just recurse infinitely.
Upvotes: 1