start_stop_daemon.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini start-stop-daemon implementation(s) for busybox
  4. *
  5. * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
  6. * Adapted for busybox David Kimdon <dwhedon@gordian.com>
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. /*
  11. This is how it is supposed to work:
  12. start-stop-daemon [OPTIONS] [--start|--stop] [[--] ARGS]
  13. One (only) of these must be given:
  14. -S,--start Start
  15. -K,--stop Stop
  16. -T,--status Check for the existence of a process, return exitcode (since version 1.16.1)
  17. 0 - program is running
  18. 1 - program is not running and the pid file exists
  19. 3 - program is not running
  20. 4 - can't determine program status
  21. Search for matching processes.
  22. If --stop is given, stop all matching processes (by sending a signal).
  23. If --start is given, start a new process unless a matching process was found.
  24. Options controlling process matching
  25. (if multiple conditions are specified, all must match):
  26. -u,--user USERNAME|UID Only consider this user's processes
  27. -n,--name PROCESS_NAME Look for processes by matching PROCESS_NAME
  28. with comm field in /proc/$PID/stat.
  29. Only basename is compared:
  30. "ntpd" == "./ntpd" == "/path/to/ntpd".
  31. [TODO: can PROCESS_NAME be a full pathname? Should we require full match then
  32. with /proc/$PID/exe or argv[0] (comm can't be matched, it never contains path)]
  33. -x,--exec EXECUTABLE Look for processes that were started with this
  34. command in /proc/$PID/exe and /proc/$PID/cmdline
  35. (/proc/$PID/cmdline is a bbox extension)
  36. Unlike -n, we match against the full path:
  37. "ntpd" != "./ntpd" != "/path/to/ntpd"
  38. -p,--pidfile PID_FILE Look for processes with PID from this file
  39. --pid PID Look for process with this pid (since version 1.17.6)
  40. --ppid PPID Look for processes with parent pid (since version 1.17.7)
  41. Options which are valid for --start only:
  42. -x,--exec EXECUTABLE Program to run (1st arg of execvp).
  43. If no -x, EXECUTABLE is taken from ARGS[0]
  44. -a,--startas NAME argv[0] (defaults to EXECUTABLE)
  45. -b,--background Put process into background
  46. -O,--output FILE Redirect stdout and stderr to FILE when forcing the
  47. daemon into the background (since version 1.20.6).
  48. Requires --background and absolute pathname (tested with 1.21.22).
  49. Uses O_CREAT|O_APPEND!
  50. If execv fails, error message goes to FILE.
  51. -N,--nicelevel N Add N to process' nice level
  52. -c,--chuid USER[:[GRP]] Change to specified user [and group]
  53. -m,--make-pidfile Write PID to the pidfile
  54. (both -m and -p must be given!)
  55. -P,--procsched policy:priority
  56. This alters the process scheduler policy and priority of the
  57. process before starting it (since version 1.15.0). The
  58. priority can be optionally specified by appending a :
  59. followed by the value. The default priority is 0. The
  60. currently supported policy values are other, fifo and rr.
  61. -r,--chroot DIR Change directory and chroot to DIR before starting the
  62. process. Please note that the pidfile is also written after
  63. the chroot.
  64. -d,--chdir DIR Change directory to DIR before starting the process. This is
  65. done after the chroot if the -r|--chroot option is set.
  66. When not specified, start-stop-daemon will change directory to the
  67. root directory before starting the process.
  68. ^^^^ Gentoo does not have the default chdir("/"). Debian does.
  69. Tested -S with 1.21.22:
  70. "start-stop-daemon -S -x /bin/pwd" is the minimum needed to run pwd.
  71. "start-stop-daemon -S -a /bin/pwd -n pwd" works too.
  72. "start-stop-daemon -S -a /bin/pwd" does NOT work.
  73. Earlier versions were less picky (which? Or is it only Gentoo's clone?)
  74. Options which are valid for --stop only:
  75. -s,--signal SIG Signal to send (default:TERM)
  76. -t,--test Exit with status 0 if process is found
  77. (we don't actually start or stop daemons)
  78. --remove-pidfile Used when stopping a program that does not remove its own pid
  79. file (since version 1.17.19). Requires -p PIDFILE?
  80. Misc options:
  81. -o,--oknodo Exit with status 0 if nothing is done
  82. -q,--quiet Quiet
  83. -v,--verbose Verbose
  84. */
  85. //config:config START_STOP_DAEMON
  86. //config: bool "start-stop-daemon (12 kb)"
  87. //config: default y
  88. //config: help
  89. //config: start-stop-daemon is used to control the creation and
  90. //config: termination of system-level processes, usually the ones
  91. //config: started during the startup of the system.
  92. //config:
  93. //config:config FEATURE_START_STOP_DAEMON_LONG_OPTIONS
  94. //config: bool "Enable long options"
  95. //config: default y
  96. //config: depends on START_STOP_DAEMON && LONG_OPTS
  97. //config:
  98. //config:config FEATURE_START_STOP_DAEMON_FANCY
  99. //config: bool "Support additional arguments"
  100. //config: default y
  101. //config: depends on START_STOP_DAEMON
  102. //config: help
  103. //config: -o|--oknodo ignored since we exit with 0 anyway
  104. //config: -v|--verbose
  105. //config: -N|--nicelevel N
  106. //applet:IF_START_STOP_DAEMON(APPLET_ODDNAME(start-stop-daemon, start_stop_daemon, BB_DIR_SBIN, BB_SUID_DROP, start_stop_daemon))
  107. /* not NOEXEC: uses bb_common_bufsiz1 */
  108. //kbuild:lib-$(CONFIG_START_STOP_DAEMON) += start_stop_daemon.o
  109. //usage:#define start_stop_daemon_trivial_usage
  110. //usage: "-S|-K [OPTIONS] [-- ARGS]"
  111. //usage:#define start_stop_daemon_full_usage "\n\n"
  112. //usage: "Search for matching processes, and then\n"
  113. //usage: "-S: start a process unless a matching process is found\n"
  114. //usage: "-K: stop all matching processes\n"
  115. //usage: "\nProcess matching:"
  116. //usage: "\n -u USERNAME|UID Match only this user's processes"
  117. //usage: "\n -n NAME Match processes with NAME"
  118. //usage: "\n in comm field in /proc/PID/stat"
  119. //usage: "\n -x EXECUTABLE Match processes with this command"
  120. //usage: "\n in /proc/PID/cmdline"
  121. //usage: "\n -p FILE Match a process with PID from FILE"
  122. //usage: "\n All specified conditions must match"
  123. //usage: "\n-S only:"
  124. //usage: "\n -x EXECUTABLE Program to run"
  125. //usage: "\n -a NAME Zeroth argument"
  126. //usage: "\n -b Background"
  127. //usage: "\n -O FILE Append stdout and stderr to FILE"
  128. //usage: IF_FEATURE_START_STOP_DAEMON_FANCY(
  129. //usage: "\n -N N Change nice level"
  130. //usage: )
  131. //usage: "\n -c USER[:[GRP]] Change user/group"
  132. //usage: "\n -d DIR Change to DIR"
  133. //usage: "\n -m Write PID to pidfile specified by -p"
  134. //usage: "\n-K only:"
  135. //usage: "\n -s SIG Signal to send"
  136. //usage: "\n -t Match only, exit with 0 if found"
  137. //usage: "\nOther:"
  138. //usage: IF_FEATURE_START_STOP_DAEMON_FANCY(
  139. //usage: "\n -o Exit with status 0 if nothing is done"
  140. //usage: "\n -v Verbose"
  141. //usage: "\n -q Quiet"
  142. //usage: )
  143. /* Override ENABLE_FEATURE_PIDFILE */
  144. #define WANT_PIDFILE 1
  145. #include "libbb.h"
  146. #include "common_bufsiz.h"
  147. struct pid_list {
  148. struct pid_list *next;
  149. pid_t pid;
  150. };
  151. enum {
  152. CTX_STOP = (1 << 0),
  153. CTX_START = (1 << 1),
  154. OPT_BACKGROUND = (1 << 2), // -b
  155. OPT_QUIET = (1 << 3), // -q
  156. OPT_TEST = (1 << 4), // -t
  157. OPT_MAKEPID = (1 << 5), // -m
  158. OPT_a = (1 << 6), // -a
  159. OPT_n = (1 << 7), // -n
  160. OPT_s = (1 << 8), // -s
  161. OPT_u = (1 << 9), // -u
  162. OPT_c = (1 << 10), // -c
  163. OPT_d = (1 << 11), // -d
  164. OPT_x = (1 << 12), // -x
  165. OPT_p = (1 << 13), // -p
  166. OPT_OUTPUT = (1 << 14), // -O
  167. OPT_OKNODO = (1 << 15) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -o
  168. OPT_VERBOSE = (1 << 16) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -v
  169. OPT_NICELEVEL = (1 << 17) * ENABLE_FEATURE_START_STOP_DAEMON_FANCY, // -N
  170. };
  171. #define QUIET (option_mask32 & OPT_QUIET)
  172. #define TEST (option_mask32 & OPT_TEST)
  173. struct globals {
  174. struct pid_list *found_procs;
  175. const char *userspec;
  176. const char *cmdname;
  177. const char *execname;
  178. const char *pidfile;
  179. char *execname_cmpbuf;
  180. unsigned execname_sizeof;
  181. int user_id;
  182. smallint signal_nr;
  183. #ifdef OLDER_VERSION_OF_X
  184. struct stat execstat;
  185. #endif
  186. } FIX_ALIASING;
  187. #define G (*(struct globals*)bb_common_bufsiz1)
  188. #define userspec (G.userspec )
  189. #define cmdname (G.cmdname )
  190. #define execname (G.execname )
  191. #define pidfile (G.pidfile )
  192. #define user_id (G.user_id )
  193. #define signal_nr (G.signal_nr )
  194. #define INIT_G() do { \
  195. setup_common_bufsiz(); \
  196. user_id = -1; \
  197. signal_nr = 15; \
  198. } while (0)
  199. #ifdef OLDER_VERSION_OF_X
  200. /* -x,--exec EXECUTABLE
  201. * Look for processes with matching /proc/$PID/exe.
  202. * Match is performed using device+inode.
  203. */
  204. static int pid_is_exec(pid_t pid)
  205. {
  206. struct stat st;
  207. char buf[sizeof("/proc/%u/exe") + sizeof(int)*3];
  208. sprintf(buf, "/proc/%u/exe", (unsigned)pid);
  209. if (stat(buf, &st) < 0)
  210. return 0;
  211. if (st.st_dev == G.execstat.st_dev
  212. && st.st_ino == G.execstat.st_ino)
  213. return 1;
  214. return 0;
  215. }
  216. #else
  217. static int pid_is_exec(pid_t pid)
  218. {
  219. ssize_t bytes;
  220. char buf[sizeof("/proc/%u/cmdline") + sizeof(int)*3];
  221. char *procname, *exelink;
  222. int match;
  223. procname = buf + sprintf(buf, "/proc/%u/exe", (unsigned)pid) - 3;
  224. exelink = xmalloc_readlink(buf);
  225. match = (exelink && strcmp(execname, exelink) == 0);
  226. free(exelink);
  227. if (match)
  228. return match;
  229. strcpy(procname, "cmdline");
  230. bytes = open_read_close(buf, G.execname_cmpbuf, G.execname_sizeof);
  231. if (bytes > 0) {
  232. G.execname_cmpbuf[bytes] = '\0';
  233. return strcmp(execname, G.execname_cmpbuf) == 0;
  234. }
  235. return 0;
  236. }
  237. #endif
  238. static int pid_is_name(pid_t pid)
  239. {
  240. /* /proc/PID/stat is "PID (comm_15_bytes_max) ..." */
  241. char buf[32]; /* should be enough */
  242. char *p, *pe;
  243. sprintf(buf, "/proc/%u/stat", (unsigned)pid);
  244. if (open_read_close(buf, buf, sizeof(buf) - 1) < 0)
  245. return 0;
  246. buf[sizeof(buf) - 1] = '\0'; /* paranoia */
  247. p = strchr(buf, '(');
  248. if (!p)
  249. return 0;
  250. pe = strrchr(++p, ')');
  251. if (!pe)
  252. return 0;
  253. *pe = '\0';
  254. /* we require comm to match and to not be truncated */
  255. /* in Linux, if comm is 15 chars, it may be a truncated
  256. * name, so we don't allow that to match */
  257. if (strlen(p) >= COMM_LEN - 1) /* COMM_LEN is 16 */
  258. return 0;
  259. return strcmp(p, cmdname) == 0;
  260. }
  261. static int pid_is_user(int pid)
  262. {
  263. struct stat sb;
  264. char buf[sizeof("/proc/") + sizeof(int)*3];
  265. sprintf(buf, "/proc/%u", (unsigned)pid);
  266. if (stat(buf, &sb) != 0)
  267. return 0;
  268. return (sb.st_uid == (uid_t)user_id);
  269. }
  270. static void check(int pid)
  271. {
  272. struct pid_list *p;
  273. if (execname && !pid_is_exec(pid)) {
  274. return;
  275. }
  276. if (cmdname && !pid_is_name(pid)) {
  277. return;
  278. }
  279. if (userspec && !pid_is_user(pid)) {
  280. return;
  281. }
  282. p = xmalloc(sizeof(*p));
  283. p->next = G.found_procs;
  284. p->pid = pid;
  285. G.found_procs = p;
  286. }
  287. static void do_pidfile(void)
  288. {
  289. FILE *f;
  290. unsigned pid;
  291. f = fopen_for_read(pidfile);
  292. if (f) {
  293. if (fscanf(f, "%u", &pid) == 1)
  294. check(pid);
  295. fclose(f);
  296. } else if (errno != ENOENT)
  297. bb_perror_msg_and_die("open pidfile %s", pidfile);
  298. }
  299. static void do_procinit(void)
  300. {
  301. DIR *procdir;
  302. struct dirent *entry;
  303. int pid;
  304. if (pidfile) {
  305. do_pidfile();
  306. return;
  307. }
  308. procdir = xopendir("/proc");
  309. pid = 0;
  310. while (1) {
  311. errno = 0; /* clear any previous error */
  312. entry = readdir(procdir);
  313. // TODO: this check is too generic, it's better
  314. // to check for exact errno(s) which mean that we got stale entry
  315. if (errno) /* Stale entry, process has died after opendir */
  316. continue;
  317. if (!entry) /* EOF, no more entries */
  318. break;
  319. pid = bb_strtou(entry->d_name, NULL, 10);
  320. if (errno) /* NaN */
  321. continue;
  322. check(pid);
  323. }
  324. closedir(procdir);
  325. if (!pid)
  326. bb_simple_error_msg_and_die("nothing in /proc - not mounted?");
  327. }
  328. static int do_stop(void)
  329. {
  330. const char *what;
  331. struct pid_list *p;
  332. int killed = 0;
  333. if (cmdname) {
  334. if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(cmdname);
  335. if (!ENABLE_FEATURE_CLEAN_UP) what = cmdname;
  336. } else if (execname) {
  337. if (ENABLE_FEATURE_CLEAN_UP) what = xstrdup(execname);
  338. if (!ENABLE_FEATURE_CLEAN_UP) what = execname;
  339. } else if (pidfile) {
  340. what = xasprintf("process in pidfile '%s'", pidfile);
  341. } else if (userspec) {
  342. what = xasprintf("process(es) owned by '%s'", userspec);
  343. } else {
  344. bb_simple_error_msg_and_die("internal error, please report");
  345. }
  346. if (!G.found_procs) {
  347. if (!QUIET)
  348. printf("no %s found; none killed\n", what);
  349. killed = -1;
  350. goto ret;
  351. }
  352. for (p = G.found_procs; p; p = p->next) {
  353. if (kill(p->pid, TEST ? 0 : signal_nr) == 0) {
  354. killed++;
  355. } else {
  356. bb_perror_msg("warning: killing process %u", (unsigned)p->pid);
  357. p->pid = 0;
  358. if (TEST) {
  359. /* Example: -K --test --pidfile PIDFILE detected
  360. * that PIDFILE's pid doesn't exist */
  361. killed = -1;
  362. goto ret;
  363. }
  364. }
  365. }
  366. if (!QUIET && killed) {
  367. printf("stopped %s (pid", what);
  368. for (p = G.found_procs; p; p = p->next)
  369. if (p->pid)
  370. printf(" %u", (unsigned)p->pid);
  371. puts(")");
  372. }
  373. ret:
  374. if (ENABLE_FEATURE_CLEAN_UP)
  375. free((char *)what);
  376. return killed;
  377. }
  378. #if ENABLE_FEATURE_START_STOP_DAEMON_LONG_OPTIONS
  379. static const char start_stop_daemon_longopts[] ALIGN1 =
  380. "stop\0" No_argument "K"
  381. "start\0" No_argument "S"
  382. "background\0" No_argument "b"
  383. "quiet\0" No_argument "q"
  384. "test\0" No_argument "t"
  385. "make-pidfile\0" No_argument "m"
  386. "output\0" Required_argument "O"
  387. # if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
  388. "oknodo\0" No_argument "o"
  389. "verbose\0" No_argument "v"
  390. "nicelevel\0" Required_argument "N"
  391. # endif
  392. "startas\0" Required_argument "a"
  393. "name\0" Required_argument "n"
  394. "signal\0" Required_argument "s"
  395. "user\0" Required_argument "u"
  396. "chuid\0" Required_argument "c"
  397. "chdir\0" Required_argument "d"
  398. "exec\0" Required_argument "x"
  399. "pidfile\0" Required_argument "p"
  400. # if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
  401. "retry\0" Required_argument "R"
  402. # endif
  403. ;
  404. # define GETOPT32 getopt32long
  405. # define LONGOPTS start_stop_daemon_longopts,
  406. #else
  407. # define GETOPT32 getopt32
  408. # define LONGOPTS
  409. #endif
  410. int start_stop_daemon_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  411. int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
  412. {
  413. unsigned opt;
  414. const char *signame;
  415. const char *startas = NULL;
  416. char *chuid;
  417. const char *chdir;
  418. const char *output = NULL;
  419. #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
  420. // const char *retry_arg = NULL;
  421. // int retries = -1;
  422. const char *opt_N;
  423. #endif
  424. INIT_G();
  425. opt = GETOPT32(argv, "^"
  426. "KSbqtma:n:s:u:c:d:x:p:O:"
  427. IF_FEATURE_START_STOP_DAEMON_FANCY("ovN:R:")
  428. "\0"
  429. "K:S:K--S:S--K"
  430. /* -K or -S is required; they are mutually exclusive */
  431. ":m?p" /* -p is required if -m is given */
  432. ":K?xpun" /* -xpun (at least one) is required if -K is given */
  433. /* (the above does not seem to be enforced by Gentoo, it does nothing
  434. * if no matching is specified with -K, and it ignores ARGS
  435. * - does not take ARGS[0] as program name to kill)
  436. */
  437. // ":S?xa" /* -xa (at least one) is required if -S is given */
  438. //Gentoo clone: "start-stop-daemon -S -- sleep 5" is a valid invocation
  439. IF_FEATURE_START_STOP_DAEMON_FANCY(":q-v") /* -q turns off -v */
  440. ,
  441. LONGOPTS
  442. &startas, &cmdname, &signame, &userspec, &chuid, &chdir, &execname, &pidfile, &output
  443. IF_FEATURE_START_STOP_DAEMON_FANCY(,&opt_N)
  444. /* We accept and ignore -R <param> / --retry <param> */
  445. IF_FEATURE_START_STOP_DAEMON_FANCY(,NULL)
  446. );
  447. //-O requires --background and absolute pathname (tested with 1.21.22).
  448. //We don't bother requiring that (smaller code):
  449. //#if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
  450. // if ((opt & OPT_OUTPUT) && !(opt & OPT_BACKGROUND))
  451. // bb_show_usage();
  452. //#endif
  453. if (opt & OPT_s) {
  454. signal_nr = get_signum(signame);
  455. if (signal_nr < 0) bb_show_usage();
  456. }
  457. //argc -= optind;
  458. argv += optind;
  459. // ARGS contains zeroth arg if -x/-a is not given, else it starts with 1st arg.
  460. // These will try to execute "[/bin/]sleep 5":
  461. // "start-stop-daemon -S -- sleep 5"
  462. // "start-stop-daemon -S -x /bin/sleep -- 5"
  463. // "start-stop-daemon -S -a sleep -- 5"
  464. // NB: -n option does _not_ behave in this way: this will try to execute "5":
  465. // "start-stop-daemon -S -n sleep -- 5"
  466. if (opt & CTX_START) {
  467. if (!execname) { /* -x is not given */
  468. execname = startas;
  469. if (!execname) { /* neither -x nor -a is given */
  470. execname = argv[0];
  471. if (!execname)
  472. bb_show_usage();
  473. argv++;
  474. }
  475. }
  476. if (!startas) /* -a is not given: use -x EXECUTABLE or argv[0] */
  477. startas = execname;
  478. *--argv = (char *)startas;
  479. }
  480. if (execname) {
  481. G.execname_sizeof = strlen(execname) + 1;
  482. G.execname_cmpbuf = xmalloc(G.execname_sizeof + 1);
  483. }
  484. // IF_FEATURE_START_STOP_DAEMON_FANCY(
  485. // if (retry_arg)
  486. // retries = xatoi_positive(retry_arg);
  487. // )
  488. if (userspec) {
  489. user_id = bb_strtou(userspec, NULL, 10);
  490. if (errno)
  491. user_id = xuname2uid(userspec);
  492. }
  493. /* Both start and stop need to know current processes */
  494. do_procinit();
  495. if (opt & CTX_STOP) {
  496. int i = do_stop();
  497. return (opt & OPT_OKNODO) ? 0 : (i <= 0);
  498. }
  499. /* else: CTX_START (-S). execname can't be NULL. */
  500. if (G.found_procs) {
  501. if (!QUIET)
  502. printf("%s is already running\n", execname);
  503. return !(opt & OPT_OKNODO);
  504. }
  505. #ifdef OLDER_VERSION_OF_X
  506. if (execname)
  507. xstat(execname, &G.execstat);
  508. #endif
  509. if (opt & OPT_BACKGROUND) {
  510. /* Daemons usually call bb_daemonize_or_rexec(), but SSD can do
  511. * without: SSD is not itself a daemon, it _execs_ a daemon.
  512. * The usual NOMMU problem of "child can't run indefinitely,
  513. * it must exec" does not bite us: we exec anyway.
  514. *
  515. * bb_daemonize(DAEMON_DEVNULL_STDIO | DAEMON_CLOSE_EXTRA_FDS | DAEMON_DOUBLE_FORK)
  516. * can be used on MMU systems, but use of vfork()
  517. * is preferable since we want to create pidfile
  518. * _before_ parent returns, and vfork() on Linux
  519. * ensures that (by blocking parent until exec in the child).
  520. */
  521. pid_t pid = xvfork();
  522. if (pid != 0) {
  523. /* Parent */
  524. /* why _exit? the child may have changed the stack,
  525. * so "return 0" may do bad things
  526. */
  527. _exit_SUCCESS();
  528. }
  529. /* Child */
  530. setsid(); /* detach from controlling tty */
  531. /* Redirect stdin to /dev/null, close extra FDs */
  532. /* Testcase: "start-stop-daemon -Sb -d /does/not/exist usleep 1" should not eat error message */
  533. bb_daemon_helper(DAEMON_DEVNULL_STDIN + DAEMON_CLOSE_EXTRA_FDS);
  534. if (!output)
  535. output = bb_dev_null; /* redirect output just before execv */
  536. /* On Linux, session leader can acquire ctty
  537. * unknowingly, by opening a tty.
  538. * Prevent this: stop being a session leader.
  539. */
  540. pid = xvfork();
  541. if (pid != 0)
  542. _exit_SUCCESS(); /* Parent */
  543. }
  544. if (opt & OPT_MAKEPID) {
  545. /* User wants _us_ to make the pidfile */
  546. write_pidfile(pidfile);
  547. }
  548. #if ENABLE_FEATURE_START_STOP_DAEMON_FANCY
  549. if (opt & OPT_NICELEVEL) {
  550. /* Set process priority (must be before OPT_c) */
  551. int prio = getpriority(PRIO_PROCESS, 0) + xatoi_range(opt_N, INT_MIN/2, INT_MAX/2);
  552. if (setpriority(PRIO_PROCESS, 0, prio) < 0) {
  553. bb_perror_msg_and_die("setpriority(%d)", prio);
  554. }
  555. }
  556. #endif
  557. if (opt & OPT_c) {
  558. struct bb_uidgid_t ugid;
  559. parse_chown_usergroup_or_die(&ugid, chuid);
  560. if (ugid.uid != (uid_t) -1L) {
  561. struct passwd *pw = xgetpwuid(ugid.uid);
  562. if (ugid.gid != (gid_t) -1L)
  563. pw->pw_gid = ugid.gid;
  564. /* initgroups, setgid, setuid: */
  565. change_identity(pw);
  566. } else if (ugid.gid != (gid_t) -1L) {
  567. xsetgid(ugid.gid);
  568. setgroups(1, &ugid.gid);
  569. }
  570. }
  571. if (opt & OPT_d) {
  572. xchdir(chdir);
  573. }
  574. if (output) {
  575. int outfd = xopen(output, O_WRONLY | O_CREAT | O_APPEND);
  576. xmove_fd(outfd, STDOUT_FILENO);
  577. xdup2(STDOUT_FILENO, STDERR_FILENO);
  578. /* on execv error, the message goes to -O file. This is intended */
  579. }
  580. /* Try:
  581. * strace -oLOG start-stop-daemon -S -x /bin/usleep -a qwerty 500000
  582. * should exec "/bin/usleep", but argv[0] should be "qwerty":
  583. */
  584. execvp(execname, argv);
  585. bb_perror_msg_and_die("can't execute '%s'", startas);
  586. }