0

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; } 
12
  • 2
    Please format your code. Commented Nov 7, 2018 at 20:06
  • You can only safely make async-signal-safe function calls from within a signal handler. printf() is not async-signal-safe. See pubs.opengroup.org/onlinepubs/9699919799/functions/… Commented Nov 7, 2018 at 20:06
  • 3
    I see no case, and no switch Commented Nov 7, 2018 at 20:09
  • 1
    @TimRandall He's edited that out of the question, but now I think he was asking why it switched from lowercase sigaction to mixed case Sigaction, not about case and switch statements. Commented Nov 7, 2018 at 20:23
  • 1
    Yes, but the point about the Minimal, Complete, and Verifiable example is that we don't have to fumble around asking whether a typo is a real typo or an accidental typo, or whether the code is the actual code or only resembles it. Commented Nov 7, 2018 at 20:27

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, dude!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.