Advertisement
Guest User

Untitled

a guest
May 21st, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <signal.h>
  5.  
  6. uint32_t one = 1;
  7. volatile int flag1 = 0;
  8. volatile int flag2 = 0;
  9. volatile int counter = 0;
  10. uint32_t mask_host = ((uint32_t) 1 << 16) - 1;
  11. uint32_t mask_net = ((uint32_t) 1 << 30) - ((uint32_t) 1 << 16);
  12.  
  13. int is_ipv4B(uint32_t addr) {
  14.     if ((addr & (one << 31)) && !(addr & (one << 30))) {
  15.         return 1;
  16.     }
  17.     return 0;
  18. }
  19.  
  20. uint32_t get_elem(uint32_t addr) {
  21.     uint32_t res;
  22.     if (flag1) {
  23.         res = addr & mask_host;
  24.     } else {
  25.         res = (addr & mask_net) >> 16;
  26.     }
  27.     return res;
  28. }
  29.  
  30. void handler(int signo) {
  31.     if (signo == SIGUSR1) {
  32.         flag1 = !flag1;
  33.         ++counter;
  34.         if (counter == 5) {
  35.             _exit(0);
  36.         }
  37.     } else if (signo == SIGUSR2) {
  38.         flag2 = 1;
  39.     }
  40. }
  41.  
  42.  
  43. int main() {
  44.     struct sigaction sa = { .sa_handler = handler, .sa_flags = SA_RESTART };
  45.     sigaction(SIGUSR1, &sa, NULL);
  46.     sigaction(SIGUSR2, &sa, NULL);
  47.  
  48.     sigset_t mask1, mask2;
  49.     sigemptyset(&mask1);
  50.     sigaddset(&mask1, SIGUSR1);
  51.     sigaddset(&mask1, SIGUSR2);
  52.     sigprocmask(SIG_BLOCK, &mask1, &mask2);
  53.  
  54.     printf("%d\n", getpid());
  55.     fflush(stdout);
  56.     while (1) {
  57.         while (!flag2) {
  58.             sigsuspend(&mask2);
  59.         }
  60.         if (flag2) {
  61.             uint32_t num;
  62.             scanf("%o", &num);
  63.             if (is_ipv4B(num)) {
  64.                 printf("%u\n", get_elem(num));
  65.             } else {
  66.                 printf("0\n");
  67.             }
  68.             fflush(stdout);
  69.         }
  70.         flag2 = 0;
  71.         break;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement