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