nohup.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* vi: set sw=4 ts=4: */
  2. /* nohup - invoke a utility immune to hangups.
  3. *
  4. * Busybox version based on nohup specification at
  5. * http://www.opengroup.org/onlinepubs/007904975/utilities/nohup.html
  6. *
  7. * Copyright 2006 Rob Landley <rob@landley.net>
  8. * Copyright 2006 Bernhard Fischer
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  11. */
  12. #include "libbb.h"
  13. /* Compat info: nohup (GNU coreutils 6.8) does this:
  14. # nohup true
  15. nohup: ignoring input and appending output to `nohup.out'
  16. # nohup true 1>/dev/null
  17. nohup: ignoring input and redirecting stderr to stdout
  18. # nohup true 2>zz
  19. # cat zz
  20. nohup: ignoring input and appending output to `nohup.out'
  21. # nohup true 2>zz 1>/dev/null
  22. # cat zz
  23. nohup: ignoring input
  24. # nohup true </dev/null 1>/dev/null
  25. nohup: redirecting stderr to stdout
  26. # nohup true </dev/null 2>zz 1>/dev/null
  27. # cat zz
  28. (nothing)
  29. #
  30. */
  31. int nohup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  32. int nohup_main(int argc, char **argv)
  33. {
  34. const char *nohupout;
  35. char *home;
  36. xfunc_error_retval = 127;
  37. if (argc < 2) bb_show_usage();
  38. /* If stdin is a tty, detach from it. */
  39. if (isatty(STDIN_FILENO)) {
  40. /* bb_error_msg("ignoring input"); */
  41. close(STDIN_FILENO);
  42. xopen(bb_dev_null, O_RDONLY); /* will be fd 0 (STDIN_FILENO) */
  43. }
  44. nohupout = "nohup.out";
  45. /* Redirect stdout to nohup.out, either in "." or in "$HOME". */
  46. if (isatty(STDOUT_FILENO)) {
  47. close(STDOUT_FILENO);
  48. if (open(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR) < 0) {
  49. home = getenv("HOME");
  50. if (home) {
  51. nohupout = concat_path_file(home, nohupout);
  52. xopen3(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR);
  53. } else {
  54. xopen(bb_dev_null, O_RDONLY); /* will be fd 1 */
  55. }
  56. }
  57. bb_error_msg("appending output to %s", nohupout);
  58. }
  59. /* If we have a tty on stderr, redirect to stdout. */
  60. if (isatty(STDERR_FILENO)) {
  61. /* if (stdout_wasnt_a_tty)
  62. bb_error_msg("redirecting stderr to stdout"); */
  63. dup2(STDOUT_FILENO, STDERR_FILENO);
  64. }
  65. signal(SIGHUP, SIG_IGN);
  66. BB_EXECVP(argv[1], argv+1);
  67. bb_simple_perror_msg_and_die(argv[1]);
  68. }