sigdemo1.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /* sigdemo1.c - shows how a signal handler works.
  2. * - run this and press Ctrl-C a few times
  3. * - counts how many times Ctrl-C is pressed and exits after a certain count
  4. */
  5. #include <stdio.h>
  6. #include <signal.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. int count = 0; // Global variable to keep track of Ctrl-C presses
  10. int max_count = 16; // The number of times Ctrl-C should be pressed before exiting
  11. void f(int signum) /* Signal handler */
  12. {
  13. printf("OUCH!");
  14. for (int i = 0; i < count; i++) { // Print the increasing number of exclamation points
  15. printf("!");
  16. }
  17. printf("\n");
  18. count++; // increment the count
  19. if (count >= max_count) {
  20. exit(0); // exit clean after max count is reached
  21. }
  22. }
  23. int main(int argc, char *argv[])
  24. {
  25. if (argc == 2) {
  26. max_count = atoi(argv[1]); // make argv[1] to an integer
  27. }
  28. signal( SIGINT, f ); // do f on SIGINT
  29. // ignore these
  30. signal( SIGTSTP, SIG_IGN );
  31. signal( SIGQUIT, SIG_IGN );
  32. // enter a main loop
  33. while (1) {
  34. sleep(1); // slow down the loop
  35. }
  36. return 0;
  37. }