3
0

setsid.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. //config:config SETSID
  17. //config: bool "setsid (3.8 kb)"
  18. //config: default y
  19. //config: help
  20. //config: setsid runs a program in a new session
  21. //applet:IF_SETSID(APPLET(setsid, BB_DIR_USR_BIN, BB_SUID_DROP))
  22. //kbuild:lib-$(CONFIG_SETSID) += setsid.o
  23. //usage:#define setsid_trivial_usage
  24. //usage: "[-c] PROG ARGS"
  25. //usage:#define setsid_full_usage "\n\n"
  26. //usage: "Run PROG in a new session. PROG will have no controlling terminal\n"
  27. //usage: "and will not be affected by keyboard signals (^C etc).\n"
  28. //usage: "\n -c Set controlling terminal to stdin"
  29. #include "libbb.h"
  30. int setsid_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  31. int setsid_main(int argc UNUSED_PARAM, char **argv)
  32. {
  33. unsigned opt;
  34. /* +: stop on first non-opt */
  35. opt = getopt32(argv, "^+" "c" "\0" "-1"/* at least one arg */);
  36. argv += optind;
  37. /* setsid() is allowed only when we are not a process group leader.
  38. * Otherwise our PID serves as PGID of some existing process group
  39. * and cannot be used as PGID of a new process group.
  40. *
  41. * Example: setsid() below fails when run alone in interactive shell:
  42. * $ setsid PROG
  43. * because shell's child (setsid) is put in a new process group.
  44. * But doesn't fail if shell is not interactive
  45. * (and therefore doesn't create process groups for pipes),
  46. * or if setsid is not the first process in the process group:
  47. * $ true | setsid PROG
  48. * or if setsid is executed in backquotes (`setsid PROG`)...
  49. */
  50. if (setsid() < 0) {
  51. pid_t pid = fork_or_rexec(argv);
  52. if (pid != 0) {
  53. /* parent */
  54. /* TODO:
  55. * we can waitpid(pid, &status, 0) and then even
  56. * emulate exitcode, making the behavior consistent
  57. * in both forked and non forked cases.
  58. * However, the code is larger and upstream
  59. * does not do such trick.
  60. */
  61. return EXIT_SUCCESS;
  62. }
  63. /* child */
  64. /* now there should be no error: */
  65. setsid();
  66. }
  67. if (opt) {
  68. /* -c: set (with stealing) controlling tty */
  69. ioctl(0, TIOCSCTTY, 1);
  70. }
  71. BB_EXECVP_or_die(argv);
  72. }