bg.c 2.3 KB

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