3
0

nohup.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. int nohup_main(int argc, char **argv);
  14. int nohup_main(int argc, char **argv)
  15. {
  16. int nullfd;
  17. const char *nohupout;
  18. char *home = NULL;
  19. xfunc_error_retval = 127;
  20. if (argc < 2) bb_show_usage();
  21. nullfd = xopen(bb_dev_null, O_WRONLY|O_APPEND);
  22. /* If stdin is a tty, detach from it. */
  23. if (isatty(STDIN_FILENO))
  24. dup2(nullfd, STDIN_FILENO);
  25. nohupout = "nohup.out";
  26. /* Redirect stdout to nohup.out, either in "." or in "$HOME". */
  27. if (isatty(STDOUT_FILENO)) {
  28. close(STDOUT_FILENO);
  29. if (open(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR) < 0) {
  30. home = getenv("HOME");
  31. if (home) {
  32. nohupout = concat_path_file(home, nohupout);
  33. xopen3(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR);
  34. }
  35. }
  36. } else dup2(nullfd, STDOUT_FILENO);
  37. /* If we have a tty on stderr, announce filename and redirect to stdout.
  38. * Else redirect to /dev/null.
  39. */
  40. if (isatty(STDERR_FILENO)) {
  41. bb_error_msg("appending to %s", nohupout);
  42. dup2(STDOUT_FILENO, STDERR_FILENO);
  43. } else dup2(nullfd, STDERR_FILENO);
  44. if (nullfd > 2)
  45. close(nullfd);
  46. signal(SIGHUP, SIG_IGN);
  47. BB_EXECVP(argv[1], argv+1);
  48. if (ENABLE_FEATURE_CLEAN_UP && home)
  49. free((char*)nohupout);
  50. bb_perror_msg_and_die("%s", argv[1]);
  51. }