bg.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. pid_t
  21. do_fork()
  22. {
  23. pid_t pid = 0;
  24. if (daemon(1, 1))
  25. fatal(strerror(errno), 0);
  26. pid = getpid();
  27. writepid(conf.bot->pid_file, pid);
  28. lastfork = now;
  29. return pid;
  30. }
  31. void
  32. writepid(const char *pidfile, pid_t pid)
  33. {
  34. FILE *fp = NULL;
  35. /* Need to attempt to write pid now, not later. */
  36. unlink(pidfile);
  37. if ((fp = fopen(pidfile, "w"))) {
  38. fprintf(fp, "%u\n", pid);
  39. if (fflush(fp)) {
  40. /* Kill bot incase a botchk is run from crond. */
  41. printf(EGG_NOWRITE, pidfile);
  42. printf(" Try freeing some disk space\n");
  43. fclose(fp);
  44. unlink(pidfile);
  45. exit(1);
  46. } else
  47. fclose(fp);
  48. } else
  49. printf(EGG_NOWRITE, pidfile);
  50. }
  51. static void
  52. init_watcher()
  53. {
  54. if (conf.watcher) {
  55. int x = 0;
  56. pid_t parent = getpid();
  57. 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 */
  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. }
  91. }