bg.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. extern char pid_file[], botnetnick[];
  12. extern time_t lastfork, now;
  13. /* Do everything we normally do after we have split off a new
  14. * process to the background. This includes writing a PID file
  15. * and informing the user of the split.
  16. */
  17. static void bg_do_detach(pid_t p)
  18. {
  19. FILE *fp;
  20. /* Need to attempt to write pid now, not later. */
  21. unlink(pid_file);
  22. fp = fopen(pid_file, "w");
  23. if (fp != NULL) {
  24. fprintf(fp, "%u\n", p);
  25. if (fflush(fp)) {
  26. /* Kill bot incase a botchk is run from crond. */
  27. printf(EGG_NOWRITE, pid_file);
  28. printf(" Try freeing some disk space\n");
  29. fclose(fp);
  30. unlink(pid_file);
  31. exit(1);
  32. }
  33. fclose(fp);
  34. } else
  35. printf(EGG_NOWRITE, pid_file);
  36. #ifdef HUB
  37. printf("Launched into the background (pid: %d)\n\n", p);
  38. #else
  39. printf("%s launched into the background (pid: %d ppid: %d)\n\n", botnetnick, p, getpid());
  40. #endif
  41. #if HAVE_SETPGID
  42. setpgid(p, p);
  43. #endif
  44. exit(0);
  45. }
  46. void bg_do_split(void)
  47. {
  48. /* Split off a new process.
  49. */
  50. int xx = fork();
  51. if (xx == -1)
  52. fatal("CANNOT FORK PROCESS.", 0);
  53. if (xx != 0)
  54. bg_do_detach(xx);
  55. }
  56. void do_fork() {
  57. int xx;
  58. xx = fork();
  59. if (xx == -1)
  60. return;
  61. if (xx != 0) {
  62. FILE *fp;
  63. unlink(pid_file);
  64. fp = fopen(pid_file, "w");
  65. if (fp != NULL) {
  66. fprintf(fp, "%u\n", xx);
  67. fclose(fp);
  68. }
  69. }
  70. if (xx) {
  71. #if HAVE_SETPGID
  72. setpgid(xx, xx);
  73. #endif
  74. exit(0);
  75. }
  76. lastfork = now;
  77. }