Advertisement
Guest User

Untitled

a guest
Dec 14th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <math.h>
  2. #include <sched.h>
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7. #include <unistd.h>
  8. #include <wait.h>
  9.  
  10. sig_atomic_t timeout = 0, exit_code = 2, chld = 0;
  11.  
  12. void sigchld_handler(int signum)
  13. {
  14.     chld = 1;
  15. }
  16.  
  17. void sigalarm_handler(int signum)
  18. {
  19.     timeout = 1;
  20. }
  21.  
  22. void set_handler(int signum, void* handler, struct sigaction* action)
  23. {
  24.     action->sa_handler = handler;
  25.     action->sa_flags = SA_RESTART;
  26.     sigaction(signum, action, NULL);
  27. }
  28.  
  29. struct sigaction sigalarm_action, sigchld_action;
  30.  
  31. int main(int argc, char* argv[])
  32. {
  33.     pid_t pid = fork();
  34.     if (pid == -1) {
  35.         printf("%s\n", "signaled");
  36.         return 1;
  37.     }
  38.     if (pid == 0) {
  39.         execvp(argv[2], &argv[2]);
  40.         exit(1);
  41.     } else {
  42.         int sleep_amount = atoi(argv[1]);
  43.         set_handler(SIGALRM, sigalarm_handler, &sigalarm_action);
  44.         set_handler(SIGCHLD, sigchld_handler, &sigchld_action);
  45.         alarm(sleep_amount);
  46.         sigset_t important_mask;
  47.         sigfillset(&important_mask);
  48.         sigdelset(&important_mask, SIGALRM);
  49.         sigdelset(&important_mask, SIGCHLD);
  50.         int exit_status;
  51.         sigsuspend(&important_mask);
  52.         if (!timeout) {
  53.             waitpid(pid, &exit_status, 0);
  54.             if (WIFSIGNALED(exit_status)) {
  55.                 exit_code = 1;
  56.                 printf("%s\n", "signaled");
  57.             } else {
  58.                 printf("%s\n", "ok");
  59.                 exit_code = 0;
  60.             }
  61.         } else {
  62.             kill(pid, SIGKILL);
  63.             exit_code = 2;
  64.             waitpid(pid, &exit_status, 0);
  65.             printf("%s\n", "timeout");
  66.         }
  67.         return exit_code;
  68.     }
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement