D_L3

2019-SE-01

May 27th, 2024 (edited)
893
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <err.h>
  4. #include <time.h>
  5. #include <fcntl.h>
  6. #include <stdbool.h>
  7. #include <stdlib.h>
  8. #include <errno.h>
  9. #include <sys/wait.h>
  10. #include <string.h>
  11.  
  12. int getCode(int);
  13. bool isCondition(time_t, time_t, int, int);
  14. int writeToFile(int, time_t, time_t, int);
  15. int convert(char*);
  16.  
  17. int getCode(int status) {
  18.         if (WIFEXITED(status)) {
  19.                 return WEXITSTATUS(status);
  20.         }
  21.         return 129;
  22. }
  23.  
  24. bool isCondition(time_t start, time_t end, int code, int limit) {
  25.         return code != 0 && limit < (end - start);
  26. }
  27.  
  28. int writeToFile(int fd, time_t start, time_t end, int exitCode) {
  29.         return dprintf(fd, "%ld %ld %d\n", start, end, exitCode);
  30. }
  31.  
  32. int convert(char* str) {
  33.         if (strlen(str) != 1 || str[0] < '1' || str[1] > '9') {
  34.                 errx(5, "invalid number");
  35.         }
  36.  
  37.         return str[0] - '0';
  38. }
  39.  
  40. int main(int argc, char* argv[]) {
  41.         //argv -> P secs Q args
  42.  
  43.         if (argc < 3) {
  44.                 errx(1, "Invalid number of arguments");
  45.         }
  46.  
  47.         int limit = convert(argv[1]);
  48.  
  49.         int conditionInRow = 0;
  50.  
  51.         int fd = open("run.log", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
  52.  
  53.         if (-1 == fd) {
  54.                 err(4, "error opening/creating file");
  55.         }
  56.  
  57.         while(conditionInRow != 2) {
  58.                 pid_t pid = fork();
  59.  
  60.                 if(-1 == pid) {
  61.                         err(2, "error forking");
  62.                 }
  63.  
  64.                 if (0 == pid) {
  65.                         execvp(argv[2], argv + 2);
  66.                         err(3, "error executing");
  67.                 }
  68.  
  69.                 time_t start = time(NULL);
  70.  
  71.                 int status;
  72.                 wait(&status);
  73.  
  74.                 time_t end = time(NULL);
  75.  
  76.                 int code = getCode(status);
  77.  
  78.                 if (writeToFile(fd, start, end, code) < 0) {
  79.                         err(4, "error writing to fd");
  80.                 }
  81.  
  82.                 if (isCondition(start, end, code, limit)) {
  83.                         conditionInRow++;
  84.                 } else {
  85.                         conditionInRow = 0;
  86.                 }
  87.         }
  88.  
  89.         close(fd);
  90. }
  91.  
Advertisement
Add Comment
Please, Sign In to add comment