loop.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #include <time.h>
  6. #include <unistd.h>
  7. #include <signal.h>
  8. #include <sys/wait.h>
  9. #include <sys/types.h>
  10. #include "stdbuf.h"
  11. bool dead = false;
  12. pid_t pid = 0;
  13. void term(int signal)
  14. {
  15. dead = true;
  16. if (pid) {
  17. kill(pid, SIGTERM);
  18. sleep(2);
  19. kill(pid, SIGKILL);
  20. }
  21. exit(0);
  22. }
  23. void exec(int argc, char **argv)
  24. {
  25. char *args[argc + 1];
  26. for (int i = 0; i < argc; i++) {
  27. args[i] = argv[i];
  28. }
  29. args[argc] = NULL;
  30. char *envs[3];
  31. envs[0] = "LD_PRELOAD=" LIBSTDBUF_PATH;
  32. envs[1] = STDBUF(STDOUT_BUF, LINE_BUF);
  33. envs[2] = NULL;
  34. execvpe(argv[0], args, envs);
  35. }
  36. void putchar_tmsp(char c)
  37. {
  38. static time_t tmsp = 0;
  39. if (!tmsp) {
  40. tmsp = time(NULL);
  41. char *ctime_nonewline = ctime(&tmsp);
  42. ctime_nonewline[strlen(ctime_nonewline) - 1] = '\0';
  43. printf("[%s] ", ctime_nonewline);
  44. }
  45. putchar(c);
  46. if (c == '\n') {
  47. tmsp = 0;
  48. }
  49. }
  50. int main(int argc, char **argv)
  51. {
  52. if (argc == 1) {
  53. exit(0);
  54. }
  55. signal(SIGTERM, term);
  56. signal(SIGINT, term);
  57. while (!dead) {
  58. time_t start = time(NULL);
  59. int file_pipe[2];
  60. if (pipe(file_pipe) != 0) {
  61. fprintf(stderr, "pipe() failed!\n");
  62. exit(1);
  63. }
  64. pid = fork();
  65. if (pid == -1) {
  66. fprintf(stderr, "fork() failed!\n");
  67. exit(1);
  68. }
  69. else if (pid == 0) {
  70. dup2(file_pipe[1], STDOUT_FILENO);
  71. dup2(file_pipe[1], STDERR_FILENO);
  72. close(file_pipe[0]);
  73. close(file_pipe[1]);
  74. exec(argc - 1, &argv[1]);
  75. exit(1);
  76. }
  77. else {
  78. close(file_pipe[1]);
  79. char buffer[BUFSIZ + 1];
  80. while (1) {
  81. ssize_t size = read(file_pipe[0], buffer, BUFSIZ);
  82. if (size == 0 || size == -1) {
  83. break;
  84. }
  85. for (int i = 0; i < size; i++) {
  86. putchar_tmsp(buffer[i]);
  87. }
  88. }
  89. if (time(NULL) - start < 10) {
  90. // Suddenly, child crashed after started, retry later...
  91. sleep(5);
  92. }
  93. }
  94. }
  95. return 0;
  96. }