bg.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 "main.h"
  10. #include <signal.h>
  11. #ifdef CRAZY_TRACE
  12. #include <sys/ptrace.h>
  13. #endif
  14. time_t lastfork = 0;
  15. /* Do everything we normally do after we have split off a new
  16. * process to the background. This includes writing a PID file
  17. * and informing the user of the split.
  18. */
  19. static void bg_do_detach(pid_t) __attribute__((noreturn));
  20. static void bg_do_detach(pid_t p)
  21. {
  22. FILE *fp = NULL;
  23. /* Need to attempt to write pid now, not later. */
  24. unlink(conf.bot->pid_file);
  25. fp = fopen(conf.bot->pid_file, "w");
  26. if (fp != NULL) {
  27. fprintf(fp, "%u\n", p);
  28. if (fflush(fp)) {
  29. /* Kill bot incase a botchk is run from crond. */
  30. printf(EGG_NOWRITE, conf.bot->pid_file);
  31. printf(" Try freeing some disk space\n");
  32. fclose(fp);
  33. unlink(conf.bot->pid_file);
  34. exit(1);
  35. }
  36. fclose(fp);
  37. } else
  38. printf(EGG_NOWRITE, conf.bot->pid_file);
  39. #ifdef HUB
  40. printf("Launched into the background (pid: %d)\n\n", p);
  41. #else /* LEAF */
  42. printf("%s launched into the background (pid: %d)\n\n", conf.bot->nick, p);
  43. #endif /* HUB */
  44. #ifndef CYGWIN_HACKS
  45. setpgid(p, p);
  46. #endif /* !CYGWIN_HACKS */
  47. exit(0);
  48. }
  49. void bg_do_split(void)
  50. {
  51. /* Split off a new process.
  52. */
  53. int xx = fork();
  54. if (xx == -1)
  55. fatal("CANNOT FORK PROCESS.", 0);
  56. if (xx != 0) /* parent */
  57. bg_do_detach(xx);
  58. #ifdef CRAZY_TRACE
  59. else /* new child */
  60. /* block ptrace? */
  61. # ifdef __linux__
  62. ptrace(PTRACE_TRACEME, 0, NULL, NULL);
  63. # endif
  64. # ifdef __FreeBSD__
  65. ptrace(PT_TRACE_ME, 0, NULL, NULL);
  66. # endif
  67. #endif /* CRAZY_TRACE */
  68. }
  69. void do_fork() {
  70. int xx;
  71. xx = fork();
  72. if (xx == -1)
  73. return;
  74. if (xx != 0) {
  75. FILE *fp;
  76. unlink(conf.bot->pid_file);
  77. fp = fopen(conf.bot->pid_file, "w");
  78. if (fp != NULL) {
  79. fprintf(fp, "%u\n", xx);
  80. fclose(fp);
  81. }
  82. }
  83. if (xx) {
  84. #if HAVE_SETPGID
  85. setpgid(xx, xx);
  86. #endif
  87. exit(0);
  88. }
  89. lastfork = now;
  90. }