bg.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. * bg.c -- handles:
  3. * moving the process to the background, i.e. forking, while keeping threads
  4. * happy.
  5. *
  6. */
  7. #include "common.h"
  8. #include "bg.h"
  9. #include "thread.h"
  10. #include "main.h"
  11. #include <signal.h>
  12. #ifndef CYGWIN_HACKS
  13. #include <sys/ptrace.h>
  14. #include <sys/wait.h>
  15. #endif /* !CYGWIN_HACKS */
  16. #include <sys/types.h>
  17. #include <errno.h>
  18. #include <unistd.h>
  19. #include <string.h>
  20. time_t lastfork = 0;
  21. #ifndef CYGWIN_HACKS
  22. pid_t watcher; /* my child/watcher */
  23. static void init_watcher(pid_t);
  24. #endif /* !CYGWIN_HACKS */
  25. pid_t
  26. do_fork()
  27. {
  28. if (daemon(1, 1))
  29. fatal(strerror(errno), 0);
  30. pid_t pid = getpid();
  31. writepid(conf.bot->pid_file, pid);
  32. lastfork = now;
  33. #ifndef CYGWIN_HACKS
  34. if (conf.watcher)
  35. init_watcher(pid);
  36. #endif /* !CYGWIN_HACKS */
  37. return pid;
  38. }
  39. void
  40. writepid(const char *pidfile, pid_t pid)
  41. {
  42. FILE *fp = NULL;
  43. /* Need to attempt to write pid now, not later. */
  44. unlink(pidfile);
  45. if ((fp = fopen(pidfile, "w"))) {
  46. fprintf(fp, "%u\n", pid);
  47. if (fflush(fp)) {
  48. /* Kill bot incase a botchk is run from crond. */
  49. printf(EGG_NOWRITE, pidfile);
  50. printf(" Try freeing some disk space\n");
  51. fclose(fp);
  52. unlink(pidfile);
  53. exit(1);
  54. } else
  55. fclose(fp);
  56. } else
  57. printf(EGG_NOWRITE, pidfile);
  58. }
  59. #ifndef CYGWIN_HACKS
  60. static void
  61. init_watcher(pid_t parent)
  62. {
  63. int x = fork();
  64. if (x == -1)
  65. fatal("Could not fork off a watcher process", 0);
  66. if (x != 0) { /* parent [bot] */
  67. watcher = x;
  68. /* printf("WATCHER: %d\n", watcher); */
  69. return;
  70. } else { /* child [watcher] */
  71. watcher = getpid();
  72. /* printf("MY PARENT: %d\n", parent); */
  73. /* printf("my pid: %d\n", watcher); */
  74. if (ptrace(PT_ATTACH, parent, 0, 0) == -1)
  75. fatal("Cannot attach to parent", 0);
  76. while (1) {
  77. int status = 0, sig = 0, ret = 0;
  78. waitpid(parent, &status, 0);
  79. sig = WSTOPSIG(status);
  80. if (sig) {
  81. ret = ptrace(PT_CONTINUE, parent, (char *) 1, sig);
  82. if (ret == -1) /* send the signal! */
  83. fatal("Could not send signal to parent", 0);
  84. /* printf("Sent signal %s (%d) to parent\n", strsignal(sig), sig); */
  85. } else {
  86. ret = ptrace(PT_CONTINUE, parent, (char *) 1, 0);
  87. if (ret == -1) {
  88. if (errno == ESRCH) /* parent is gone! */
  89. exit(0); /* just exit */
  90. else
  91. fatal("Could not continue parent", 0);
  92. }
  93. }
  94. }
  95. }
  96. }
  97. #endif /* !CYGWIN_HACKS */