Is there a way to make my program work with less code?

前端 未结 2 1739
甜味超标
甜味超标 2021-01-26 10:08

I wrote the following code for a school assignment - It compiles and prints all the correct messages. But just for my own curiosity, I would like to know if my code can be shor

2条回答
  •  悲哀的现实
    2021-01-26 10:48

    static void sigHandlers(int sig)
    {
      if (sig == SIGINT)
        printf("Caught SIGINT, Existing\n");
      else if (sig == SIGUSR1)
        printf("Caught SIGUSR1\n");
      else //no need to switch since you have only 3 sig
        printf("Caught SIGUSR2\n");
      exit(EXIT_SUCCESS);
    }
    
    int main(int argc, char *argv[])
    {
      struct sigaction s[4] = {0};
    
      s[0].sa_handler = sigHandlers;
      sigemptyset(&(s[0].sa_mask));
    
      memcpy(&s[1], s, sizeof(struct sigaction));
      memcpy(&s[2], s, sizeof(struct sigaction));
    
      sigaction(SIGUSR1, &s[0], &s[3]);
      sigaction(SIGUSR2, &s[1], &s[3]);
      sigaction(SIGINT, &s[2], &s[3]);
    
      kill(getpid(), SIGUSR1);
      kill(getpid(), SIGUSR2);
      kill(getpid(), SIGINT);
    
      return 0;
    }
    

    But I'm sure you can reduce the code with #define

提交回复
热议问题