Advertisement
codegod313

Examole of handling signals (Linux)

Jun 4th, 2021
1,082
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <signal.h>
  4. #include <ncurses.h>
  5. #include <stdlib.h>
  6. #include <termios.h>
  7. #include <sys/ioctl.h>
  8. #include <string.h>
  9.  
  10.  
  11. int  _kbhit() {
  12.     static bool inited = false;
  13.     int left;
  14.  
  15.     if (!inited) {
  16.         struct termios t;
  17.         tcgetattr(0, &t);
  18.         t.c_lflag &= ~ICANON;
  19.         tcsetattr(0, TCSANOW, &t);
  20.         setbuf(stdin, NULL);
  21.         inited = true;
  22.     }
  23.  
  24.     ioctl(0, FIONREAD, &left);
  25.  
  26.     return left;
  27. }
  28.  
  29. void handle_sigusr1(int sig)
  30. {
  31.     fflush(stdout);
  32.     system("date");
  33.     FILE *f = fopen("text.txt", "a");
  34.     if(f == NULL)
  35.     {
  36.         printf("Error while opening file\n");
  37.         return;
  38.     }
  39.     char *str = (char *)malloc(sizeof(char) * 256);
  40.     strcpy(str, "aaa");
  41.     for(int i = 0; i<3; i++)
  42.     {
  43.         str[i] = 'a' + rand()%26;
  44.     }
  45.     fprintf(f,"%s\n", str);
  46.     fclose(f);
  47. }
  48.  
  49. int main()
  50. {
  51.     int pid = fork();
  52.     switch (pid)
  53.     {
  54.     case -1:
  55.         printf("Error launchong mew proces\n");
  56.         break;
  57.     case 0:
  58.     {
  59.         while (true)
  60.         {
  61.             sleep(2);
  62.             kill(getppid(), SIGUSR1);
  63.         }
  64.     }
  65.    
  66.     default:
  67.     {
  68.         struct sigaction sa;
  69.         //gsa.sa_flags = SA_RESTART;
  70.         sa.sa_handler = &handle_sigusr1;
  71.         sigaction(SIGUSR1, &sa, NULL);
  72.         while (true)
  73.         {
  74.             if(_kbhit() != 0)
  75.             {
  76.                 kill(pid, SIGKILL);
  77.                 return 0;
  78.             }
  79.         }
  80.     }
  81.         break;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement