Advertisement
Guest User

Untitled

a guest
May 21st, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include <sys/types.h>
  8. #include <sys/wait.h>
  9.  
  10. pid_t pid;
  11.  
  12. void handle_alrm(int signum)
  13. {
  14.   kill(pid, SIGTERM);
  15.   printf("timeout\n");
  16.   exit(2);
  17. }
  18.  
  19. int main(int argc , char *argv[])
  20. {  
  21.   pid = fork();
  22.  
  23.   if(pid == 0)
  24.   {
  25.     char **args = argv + 2;
  26.     execvp(argv[2], args);
  27.   }
  28.   else
  29.   {
  30.     int seconds = atoi(argv[1]);
  31.     struct sigaction action_sig;
  32.     memset(&action_sig, 0, sizeof(action_sig));
  33.     action_sig.sa_handler = handle_alrm;
  34.     action_sig.sa_flags = SA_RESTART;
  35.     sigaction(SIGALRM, &action_sig, NULL);
  36.  
  37.     alarm(seconds);
  38.     int status;
  39.     waitpid(pid, &status, 0);
  40.     alarm(0);
  41.     if (WIFEXITED(status))
  42.     {
  43.       printf("ok\n");
  44.       exit(0);
  45.     }
  46.     if (WIFSIGNALED(status))
  47.     {
  48.       printf("signaled\n");
  49.       exit(1);
  50.     }
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement