setsid.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * setsid.c -- execute a command in a new session
  4. * Rick Sladkey <jrs@world.std.com>
  5. * In the public domain.
  6. *
  7. * 1999-02-22 Arkadiusz Mickiewicz <misiek@pld.ORG.PL>
  8. * - added Native Language Support
  9. *
  10. * 2001-01-18 John Fremlin <vii@penguinpowered.com>
  11. * - fork in case we are process group leader
  12. *
  13. * 2004-11-12 Paul Fox
  14. * - busyboxed
  15. */
  16. //usage:#define setsid_trivial_usage
  17. //usage: "[-c] PROG ARGS"
  18. //usage:#define setsid_full_usage "\n\n"
  19. //usage: "Run PROG in a new session. PROG will have no controlling terminal\n"
  20. //usage: "and will not be affected by keyboard signals (^C etc).\n"
  21. //usage: "\n -c Set controlling terminal to stdin"
  22. #include "libbb.h"
  23. int setsid_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  24. int setsid_main(int argc UNUSED_PARAM, char **argv)
  25. {
  26. unsigned opt;
  27. opt_complementary = "-1"; /* at least one arg */
  28. opt = getopt32(argv, "+c"); /* +: stop on first non-opt */
  29. argv += optind;
  30. /* setsid() is allowed only when we are not a process group leader.
  31. * Otherwise our PID serves as PGID of some existing process group
  32. * and cannot be used as PGID of a new process group.
  33. *
  34. * Example: setsid() below fails when run alone in interactive shell:
  35. * $ setsid PROG
  36. * because shell's child (setsid) is put in a new process group.
  37. * But doesn't fail if shell is not interactive
  38. * (and therefore doesn't create process groups for pipes),
  39. * or if setsid is not the first process in the process group:
  40. * $ true | setsid PROG
  41. * or if setsid is executed in backquotes (`setsid PROG`)...
  42. */
  43. if (setsid() < 0) {
  44. pid_t pid = fork_or_rexec(argv);
  45. if (pid != 0) {
  46. /* parent */
  47. /* TODO:
  48. * we can waitpid(pid, &status, 0) and then even
  49. * emulate exitcode, making the behavior consistent
  50. * in both forked and non forked cases.
  51. * However, the code is larger and upstream
  52. * does not do such trick.
  53. */
  54. return EXIT_SUCCESS;
  55. }
  56. /* child */
  57. /* now there should be no error: */
  58. setsid();
  59. }
  60. if (opt) {
  61. /* -c: set (with stealing) controlling tty */
  62. ioctl(0, TIOCSCTTY, 1);
  63. }
  64. BB_EXECVP_or_die(argv);
  65. }