2 * A rewrite of the original Debian's start-stop-daemon Perl script
3 * in C (faster - it is executed many times during system startup).
5 * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
6 * public domain. Based conceptually on start-stop-daemon.pl, by Ian
7 * Jackson <ijackson@gnu.ai.mit.edu>. May be used and distributed
8 * freely for any purpose. Changes by Christian Schwarz
9 * <schwarz@monet.m.isar.de>, to make output conform to the Debian
10 * Console Message Standard, also placed in public domain. Minor
11 * changes by Klee Dienes <klee@debian.org>, also placed in the Public
14 * Changes by Ben Collins <bcollins@debian.org>, added --chuid, --background
15 * and --make-pidfile options, placed in public domain as well.
17 * Port to OpenBSD by Sontri Tomo Huynh <huynh.29@osu.edu>
18 * and Andreas Schuldei <andreas@schuldei.org>
20 * Changes by Ian Jackson: added --retry (and associated rearrangements).
26 #include <dpkg/macros.h>
28 #if defined(__linux__)
30 #elif defined(__GNU__)
32 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
34 #elif defined(__NetBSD__)
36 #elif defined(__OpenBSD__)
38 #elif defined(__DragonFly__)
39 # define OS_DragonFlyBSD
40 #elif defined(__APPLE__) && defined(__MACH__)
49 # error Unknown architecture - cannot build start-stop-daemon
52 /* NetBSD needs this to expose struct proc. */
55 #ifdef HAVE_SYS_PARAM_H
56 #include <sys/param.h>
58 #ifdef HAVE_SYS_SYSCALL_H
59 #include <sys/syscall.h>
61 #ifdef HAVE_SYS_SYSCTL_H
62 #include <sys/sysctl.h>
64 #ifdef HAVE_SYS_PROCFS_H
65 #include <sys/procfs.h>
67 #ifdef HAVE_SYS_PROC_H
70 #ifdef HAVE_SYS_USER_H
73 #ifdef HAVE_SYS_PSTAT_H
74 #include <sys/pstat.h>
76 #include <sys/types.h>
80 #include <sys/select.h>
81 #include <sys/ioctl.h>
116 #if defined(OS_Darwin)
122 #if defined(OS_FreeBSD)
123 #define KVM_MEMFILE "/dev/null"
125 #define KVM_MEMFILE NULL
129 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
132 #define SCHED_OTHER -1
133 #define SCHED_FIFO -1
137 #if defined(OS_Linux)
138 /* This comes from TASK_COMM_LEN defined in Linux' include/linux/sched.h. */
139 #define PROCESS_NAME_SIZE 15
140 #elif defined(OS_Solaris)
141 #define PROCESS_NAME_SIZE 15
142 #elif defined(OS_Darwin)
143 #define PROCESS_NAME_SIZE 16
144 #elif defined(OS_AIX)
145 /* This comes from PRFNSZ defined in AIX's <sys/procfs.h>. */
146 #define PROCESS_NAME_SIZE 16
147 #elif defined(OS_NetBSD)
148 #define PROCESS_NAME_SIZE 16
149 #elif defined(OS_OpenBSD)
150 #define PROCESS_NAME_SIZE 16
151 #elif defined(OS_FreeBSD)
152 #define PROCESS_NAME_SIZE 19
153 #elif defined(OS_DragonFlyBSD)
154 /* On DragonFlyBSD MAXCOMLEN expands to 16. */
155 #define PROCESS_NAME_SIZE MAXCOMLEN
158 #if defined(SYS_ioprio_set) && defined(linux)
159 #define HAVE_IOPRIO_SET
162 #define IOPRIO_CLASS_SHIFT 13
163 #define IOPRIO_PRIO_VALUE(class, prio) (((class) << IOPRIO_CLASS_SHIFT) | (prio))
164 #define IO_SCHED_PRIO_MIN 0
165 #define IO_SCHED_PRIO_MAX 7
168 IOPRIO_WHO_PROCESS = 1,
187 /* Time conversion constants. */
189 NANOSEC_IN_SEC = 1000000000L,
190 NANOSEC_IN_MILLISEC = 1000000L,
191 NANOSEC_IN_MICROSEC = 1000L,
194 /* The minimum polling interval, 20ms. */
195 static const long MIN_POLL_INTERVAL = 20 * NANOSEC_IN_MILLISEC;
197 static enum action_code action;
198 static bool testmode = false;
199 static int quietmode = 0;
200 static int exitnodo = 1;
201 static bool background = false;
202 static bool close_io = true;
203 static bool mpidfile = false;
204 static bool rpidfile = false;
205 static int signal_nr = SIGTERM;
206 static int user_id = -1;
207 static int runas_uid = -1;
208 static int runas_gid = -1;
209 static const char *userspec = NULL;
210 static char *changeuser = NULL;
211 static const char *changegroup = NULL;
212 static char *changeroot = NULL;
213 static const char *changedir = "/";
214 static const char *cmdname = NULL;
215 static char *execname = NULL;
216 static char *startas = NULL;
217 static pid_t match_pid = -1;
218 static pid_t match_ppid = -1;
219 static const char *pidfile = NULL;
220 static char *what_stop = NULL;
221 static const char *progname = "";
222 static int nicelevel = 0;
223 static int umask_value = -1;
225 static struct stat exec_stat;
227 static struct proc_stat_list *procset = NULL;
230 /* LSB Init Script process status exit codes. */
233 STATUS_DEAD_PIDFILE = 1,
234 STATUS_DEAD_LOCKFILE = 2,
240 struct pid_list *next;
244 static struct pid_list *found = NULL;
245 static struct pid_list *killed = NULL;
247 /* Resource scheduling policy. */
248 struct res_schedule {
249 const char *policy_name;
254 struct schedule_item {
259 /* Only seen within parse_schedule and callees. */
262 /* Seconds, signal no., or index into array. */
266 static struct res_schedule *proc_sched = NULL;
267 static struct res_schedule *io_sched = NULL;
269 static int schedule_length;
270 static struct schedule_item *schedule = NULL;
273 static void DPKG_ATTR_PRINTF(1)
274 warning(const char *format, ...)
278 fprintf(stderr, "%s: warning: ", progname);
279 va_start(arglist, format);
280 vfprintf(stderr, format, arglist);
284 static void DPKG_ATTR_NORET DPKG_ATTR_PRINTF(1)
285 fatal(const char *format, ...)
288 int errno_fatal = errno;
290 fprintf(stderr, "%s: ", progname);
291 va_start(arglist, format);
292 vfprintf(stderr, format, arglist);
295 fprintf(stderr, " (%s)\n", strerror(errno_fatal));
297 fprintf(stderr, "\n");
299 if (action == ACTION_STATUS)
300 exit(STATUS_UNKNOWN);
313 fatal("malloc(%d) failed", size);
317 xstrndup(const char *str, size_t n)
321 new_str = strndup(str, n);
324 fatal("strndup(%s, %zu) failed", str, n);
328 timespec_gettime(struct timespec *ts)
330 #if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && \
331 defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK > 0
332 if (clock_gettime(CLOCK_MONOTONIC, ts) < 0)
333 fatal("clock_gettime failed");
337 if (gettimeofday(&tv, NULL) != 0)
338 fatal("gettimeofday failed");
340 ts->tv_sec = tv.tv_sec;
341 ts->tv_nsec = tv.tv_usec * NANOSEC_IN_MICROSEC;
345 #define timespec_cmp(a, b, OP) \
346 (((a)->tv_sec == (b)->tv_sec) ? \
347 ((a)->tv_nsec OP (b)->tv_nsec) : \
348 ((a)->tv_sec OP (b)->tv_sec))
351 timespec_sub(struct timespec *a, struct timespec *b, struct timespec *res)
353 res->tv_sec = a->tv_sec - b->tv_sec;
354 res->tv_nsec = a->tv_nsec - b->tv_nsec;
355 if (res->tv_nsec < 0) {
357 res->tv_nsec += NANOSEC_IN_SEC;
362 timespec_mul(struct timespec *a, int b)
364 long nsec = a->tv_nsec * b;
367 a->tv_sec += nsec / NANOSEC_IN_SEC;
368 a->tv_nsec = nsec % NANOSEC_IN_SEC;
372 newpath(const char *dirname, const char *filename)
377 path_len = strlen(dirname) + 1 + strlen(filename) + 1;
378 path = xmalloc(path_len);
379 snprintf(path, path_len, "%s/%s", dirname, filename);
385 get_open_fd_max(void)
387 #ifdef HAVE_GETDTABLESIZE
388 return getdtablesize();
390 return sysconf(_SC_OPEN_MAX);
396 detach_controlling_tty(void)
398 #ifdef HAVE_TIOCNOTTY
401 tty_fd = open("/dev/tty", O_RDWR);
403 /* The current process does not have a controlling tty. */
407 if (ioctl(tty_fd, TIOCNOTTY, 0) != 0)
408 fatal("unable to detach controlling tty");
417 if (setpgid(0, 0) < 0)
420 detach_controlling_tty();
427 wait_for_child(pid_t pid)
433 child = waitpid(pid, &status, 0);
434 } while (child == -1 && errno == EINTR);
437 fatal("error waiting for child");
439 if (WIFEXITED(status)) {
440 int ret = WEXITSTATUS(status);
443 fatal("child returned error exit status %d", ret);
444 } else if (WIFSIGNALED(status)) {
445 int signo = WTERMSIG(status);
447 fatal("child was killed by signal %d", signo);
449 fatal("unexpected status %d waiting for child", status);
454 write_pidfile(const char *filename, pid_t pid)
459 fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);
463 fp = fdopen(fd, "w");
466 fatal("unable to open pidfile '%s' for writing", filename);
468 fprintf(fp, "%d\n", pid);
471 fatal("unable to close pidfile '%s'", filename);
475 remove_pidfile(const char *filename)
477 if (unlink(filename) < 0 && errno != ENOENT)
478 fatal("cannot remove pidfile '%s'", filename);
489 printf("Detaching to start %s...", startas);
491 /* Block SIGCHLD to allow waiting for the child process while it is
492 * performing actions, such as creating a pidfile. */
494 sigaddset(&mask, SIGCHLD);
495 if (sigprocmask(SIG_BLOCK, &mask, &oldmask) == -1)
496 fatal("cannot block SIGCHLD");
500 fatal("unable to do first fork");
501 else if (pid) { /* First Parent. */
502 /* Wait for the second parent to exit, so that if we need to
503 * perform any actions there, like creating a pidfile, we do
504 * not suffer from race conditions on return. */
510 /* Create a new session. */
512 fatal("cannot set session ID");
516 fatal("unable to do second fork");
517 else if (pid) { /* Second parent. */
518 /* Set a default umask for dumb programs, which might get
519 * overridden by the --umask option later on, so that we get
520 * a defined umask when creating the pidfille. */
523 if (mpidfile && pidfile != NULL)
524 /* User wants _us_ to make the pidfile. */
525 write_pidfile(pidfile, pid);
530 if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1)
531 fatal("cannot restore signal mask");
538 pid_list_push(struct pid_list **list, pid_t pid)
542 p = xmalloc(sizeof(*p));
549 pid_list_free(struct pid_list **list)
551 struct pid_list *here, *next;
553 for (here = *list; here != NULL; here = next) {
565 "Usage: start-stop-daemon [<option>...] <command>\n"
570 " -S, --start -- <argument>... start a program and pass <arguments> to it\n"
571 " -K, --stop stop a program\n"
572 " -T, --status get the program status\n"
573 " -H, --help print help information\n"
574 " -V, --version print version\n"
578 "Matching options (at least one is required):\n"
579 " --pid <pid> pid to check\n"
580 " --ppid <ppid> parent pid to check\n"
581 " -p, --pidfile <pid-file> pid file to check\n"
582 " -x, --exec <executable> program to start/check if it is running\n"
583 " -n, --name <process-name> process name to check\n"
584 " -u, --user <username|uid> process owner to check\n"
589 " -g, --group <group|gid> run process as this group\n"
590 " -c, --chuid <name|uid[:group|gid]>\n"
591 " change to this user/group before starting\n"
593 " -s, --signal <signal> signal to send (default TERM)\n"
594 " -a, --startas <pathname> program to start (default is <executable>)\n"
595 " -r, --chroot <directory> chroot to <directory> before starting\n"
596 " -d, --chdir <directory> change to <directory> (default is /)\n"
597 " -N, --nicelevel <incr> add incr to the process' nice level\n"
598 " -P, --procsched <policy[:prio]>\n"
599 " use <policy> with <prio> for the kernel\n"
600 " process scheduler (default prio is 0)\n"
601 " -I, --iosched <class[:prio]> use <class> with <prio> to set the IO\n"
602 " scheduler (default prio is 4)\n"
603 " -k, --umask <mask> change the umask to <mask> before starting\n"
604 " -b, --background force the process to detach\n"
605 " -C, --no-close do not close any file descriptor\n"
606 " -m, --make-pidfile create the pidfile before starting\n"
607 " --remove-pidfile delete the pidfile after stopping\n"
608 " -R, --retry <schedule> check whether processes die, and retry\n"
609 " -t, --test test mode, don't do anything\n"
610 " -o, --oknodo exit status 0 (not 1) if nothing done\n"
611 " -q, --quiet be more quiet\n"
612 " -v, --verbose be more verbose\n"
616 "Retry <schedule> is <item>|/<item>/... where <item> is one of\n"
617 " -<signal-num>|[-]<signal-name> send that signal\n"
618 " <timeout> wait that many seconds\n"
619 " forever repeat remainder forever\n"
620 "or <schedule> may be just <timeout>, meaning <signal>/<timeout>/KILL/<timeout>\n"
624 "The process scheduler <policy> can be one of:\n"
625 " other, fifo or rr\n"
629 "The IO scheduler <class> can be one of:\n"
630 " real-time, best-effort or idle\n"
636 " 1 = nothing done (=> 0 if --oknodo)\n"
637 " 2 = with --retry, processes would not die\n"
639 "Exit status with --status:\n"
640 " 0 = program is running\n"
641 " 1 = program is not running and the pid file exists\n"
642 " 3 = program is not running\n"
643 " 4 = unable to determine status\n");
649 printf("start-stop-daemon %s for Debian\n\n", VERSION);
651 printf("Written by Marek Michalkiewicz, public domain.\n");
654 static void DPKG_ATTR_NORET
655 badusage(const char *msg)
658 fprintf(stderr, "%s: %s\n", progname, msg);
659 fprintf(stderr, "Try '%s --help' for more information.\n", progname);
661 if (action == ACTION_STATUS)
662 exit(STATUS_UNKNOWN);
672 static const struct sigpair siglist[] = {
695 parse_unsigned(const char *string, int base, int *value_r)
704 value = strtol(string, &endptr, base);
705 if (string == endptr || *endptr != '\0' || errno != 0)
707 if (value < 0 || value > INT_MAX)
715 parse_pid(const char *pid_str, int *pid_num)
717 if (parse_unsigned(pid_str, 10, pid_num) != 0)
726 parse_signal(const char *sig_str, int *sig_num)
730 if (parse_unsigned(sig_str, 10, sig_num) == 0)
733 for (i = 0; i < array_count(siglist); i++) {
734 if (strcmp(sig_str, siglist[i].name) == 0) {
735 *sig_num = siglist[i].signal;
743 parse_umask(const char *string, int *value_r)
745 return parse_unsigned(string, 0, value_r);
749 validate_proc_schedule(void)
751 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
752 int prio_min, prio_max;
754 prio_min = sched_get_priority_min(proc_sched->policy);
755 prio_max = sched_get_priority_max(proc_sched->policy);
757 if (proc_sched->priority < prio_min)
758 badusage("process scheduler priority less than min");
759 if (proc_sched->priority > prio_max)
760 badusage("process scheduler priority greater than max");
765 parse_proc_schedule(const char *string)
771 policy_len = strcspn(string, ":");
772 policy_str = xstrndup(string, policy_len);
774 if (string[policy_len] == ':' &&
775 parse_unsigned(string + policy_len + 1, 10, &prio) != 0)
776 fatal("invalid process scheduler priority");
778 proc_sched = xmalloc(sizeof(*proc_sched));
779 proc_sched->policy_name = policy_str;
781 if (strcmp(policy_str, "other") == 0) {
782 proc_sched->policy = SCHED_OTHER;
783 proc_sched->priority = 0;
784 } else if (strcmp(policy_str, "fifo") == 0) {
785 proc_sched->policy = SCHED_FIFO;
786 proc_sched->priority = prio;
787 } else if (strcmp(policy_str, "rr") == 0) {
788 proc_sched->policy = SCHED_RR;
789 proc_sched->priority = prio;
791 badusage("invalid process scheduler policy");
793 validate_proc_schedule();
797 parse_io_schedule(const char *string)
803 class_len = strcspn(string, ":");
804 class_str = xstrndup(string, class_len);
806 if (string[class_len] == ':' &&
807 parse_unsigned(string + class_len + 1, 10, &prio) != 0)
808 fatal("invalid IO scheduler priority");
810 io_sched = xmalloc(sizeof(*io_sched));
811 io_sched->policy_name = class_str;
813 if (strcmp(class_str, "real-time") == 0) {
814 io_sched->policy = IOPRIO_CLASS_RT;
815 io_sched->priority = prio;
816 } else if (strcmp(class_str, "best-effort") == 0) {
817 io_sched->policy = IOPRIO_CLASS_BE;
818 io_sched->priority = prio;
819 } else if (strcmp(class_str, "idle") == 0) {
820 io_sched->policy = IOPRIO_CLASS_IDLE;
821 io_sched->priority = 7;
823 badusage("invalid IO scheduler policy");
825 if (io_sched->priority < IO_SCHED_PRIO_MIN)
826 badusage("IO scheduler priority less than min");
827 if (io_sched->priority > IO_SCHED_PRIO_MAX)
828 badusage("IO scheduler priority greater than max");
832 set_proc_schedule(struct res_schedule *sched)
834 #if defined(_POSIX_PRIORITY_SCHEDULING) && _POSIX_PRIORITY_SCHEDULING > 0
835 struct sched_param param;
837 param.sched_priority = sched->priority;
839 if (sched_setscheduler(getpid(), sched->policy, ¶m) == -1)
840 fatal("unable to set process scheduler");
844 #ifdef HAVE_IOPRIO_SET
846 ioprio_set(int which, int who, int ioprio)
848 return syscall(SYS_ioprio_set, which, who, ioprio);
853 set_io_schedule(struct res_schedule *sched)
855 #ifdef HAVE_IOPRIO_SET
858 io_sched_mask = IOPRIO_PRIO_VALUE(sched->policy, sched->priority);
859 if (ioprio_set(IOPRIO_WHO_PROCESS, getpid(), io_sched_mask) == -1)
860 warning("unable to alter IO priority to mask %i (%s)\n",
861 io_sched_mask, strerror(errno));
866 parse_schedule_item(const char *string, struct schedule_item *item)
868 const char *after_hyph;
870 if (strcmp(string, "forever") == 0) {
871 item->type = sched_forever;
872 } else if (isdigit(string[0])) {
873 item->type = sched_timeout;
874 if (parse_unsigned(string, 10, &item->value) != 0)
875 badusage("invalid timeout value in schedule");
876 } else if ((after_hyph = string + (string[0] == '-')) &&
877 parse_signal(after_hyph, &item->value) == 0) {
878 item->type = sched_signal;
880 badusage("invalid schedule item (must be [-]<signal-name>, "
881 "-<signal-number>, <timeout> or 'forever'");
886 parse_schedule(const char *schedule_str)
894 for (slash = schedule_str; *slash; slash++)
898 schedule_length = (count == 0) ? 4 : count + 1;
899 schedule = xmalloc(sizeof(*schedule) * schedule_length);
902 schedule[0].type = sched_signal;
903 schedule[0].value = signal_nr;
904 parse_schedule_item(schedule_str, &schedule[1]);
905 if (schedule[1].type != sched_timeout) {
906 badusage("--retry takes timeout, or schedule list"
907 " of at least two items");
909 schedule[2].type = sched_signal;
910 schedule[2].value = SIGKILL;
911 schedule[3] = schedule[1];
915 while (schedule_str != NULL) {
916 slash = strchr(schedule_str, '/');
917 str_len = slash ? (size_t)(slash - schedule_str) : strlen(schedule_str);
918 if (str_len >= sizeof(item_buf))
919 badusage("invalid schedule item: far too long"
920 " (you must delimit items with slashes)");
921 memcpy(item_buf, schedule_str, str_len);
922 item_buf[str_len] = '\0';
923 schedule_str = slash ? slash + 1 : NULL;
925 parse_schedule_item(item_buf, &schedule[count]);
926 if (schedule[count].type == sched_forever) {
928 badusage("invalid schedule: 'forever'"
929 " appears more than once");
935 if (repeatat == count)
936 badusage("invalid schedule: 'forever' appears last, "
937 "nothing to repeat");
939 schedule[count].type = sched_goto;
940 schedule[count].value = repeatat;
943 assert(count == schedule_length);
948 set_action(enum action_code new_action)
950 if (action == new_action)
953 if (action != ACTION_NONE)
954 badusage("only one command can be specified");
961 #define OPT_RM_PIDFILE 502
964 parse_options(int argc, char * const *argv)
966 static struct option longopts[] = {
967 { "help", 0, NULL, 'H'},
968 { "stop", 0, NULL, 'K'},
969 { "start", 0, NULL, 'S'},
970 { "status", 0, NULL, 'T'},
971 { "version", 0, NULL, 'V'},
972 { "startas", 1, NULL, 'a'},
973 { "name", 1, NULL, 'n'},
974 { "oknodo", 0, NULL, 'o'},
975 { "pid", 1, NULL, OPT_PID},
976 { "ppid", 1, NULL, OPT_PPID},
977 { "pidfile", 1, NULL, 'p'},
978 { "quiet", 0, NULL, 'q'},
979 { "signal", 1, NULL, 's'},
980 { "test", 0, NULL, 't'},
981 { "user", 1, NULL, 'u'},
982 { "group", 1, NULL, 'g'},
983 { "chroot", 1, NULL, 'r'},
984 { "verbose", 0, NULL, 'v'},
985 { "exec", 1, NULL, 'x'},
986 { "chuid", 1, NULL, 'c'},
987 { "nicelevel", 1, NULL, 'N'},
988 { "procsched", 1, NULL, 'P'},
989 { "iosched", 1, NULL, 'I'},
990 { "umask", 1, NULL, 'k'},
991 { "background", 0, NULL, 'b'},
992 { "no-close", 0, NULL, 'C'},
993 { "make-pidfile", 0, NULL, 'm'},
994 { "remove-pidfile", 0, NULL, OPT_RM_PIDFILE},
995 { "retry", 1, NULL, 'R'},
996 { "chdir", 1, NULL, 'd'},
999 const char *pid_str = NULL;
1000 const char *ppid_str = NULL;
1001 const char *umask_str = NULL;
1002 const char *signal_str = NULL;
1003 const char *schedule_str = NULL;
1004 const char *proc_schedule_str = NULL;
1005 const char *io_schedule_str = NULL;
1006 size_t changeuser_len;
1010 c = getopt_long(argc, argv,
1011 "HKSVTa:n:op:qr:s:tu:vx:c:N:P:I:k:bCmR:g:d:",
1016 case 'H': /* --help */
1019 case 'K': /* --stop */
1020 set_action(ACTION_STOP);
1022 case 'S': /* --start */
1023 set_action(ACTION_START);
1025 case 'T': /* --status */
1026 set_action(ACTION_STATUS);
1028 case 'V': /* --version */
1031 case 'a': /* --startas <pathname> */
1034 case 'n': /* --name <process-name> */
1037 case 'o': /* --oknodo */
1040 case OPT_PID: /* --pid <pid> */
1043 case OPT_PPID: /* --ppid <ppid> */
1046 case 'p': /* --pidfile <pid-file> */
1049 case 'q': /* --quiet */
1052 case 's': /* --signal <signal> */
1053 signal_str = optarg;
1055 case 't': /* --test */
1058 case 'u': /* --user <username>|<uid> */
1061 case 'v': /* --verbose */
1064 case 'x': /* --exec <executable> */
1067 case 'c': /* --chuid <username>|<uid> */
1068 /* We copy the string just in case we need the
1069 * argument later. */
1070 changeuser_len = strcspn(optarg, ":");
1071 changeuser = xstrndup(optarg, changeuser_len);
1072 if (optarg[changeuser_len] == ':') {
1073 if (optarg[changeuser_len + 1] == '\0')
1074 fatal("missing group name");
1075 changegroup = optarg + changeuser_len + 1;
1078 case 'g': /* --group <group>|<gid> */
1079 changegroup = optarg;
1081 case 'r': /* --chroot /new/root */
1082 changeroot = optarg;
1084 case 'N': /* --nice */
1085 nicelevel = atoi(optarg);
1087 case 'P': /* --procsched */
1088 proc_schedule_str = optarg;
1090 case 'I': /* --iosched */
1091 io_schedule_str = optarg;
1093 case 'k': /* --umask <mask> */
1096 case 'b': /* --background */
1099 case 'C': /* --no-close */
1102 case 'm': /* --make-pidfile */
1105 case OPT_RM_PIDFILE: /* --remove-pidfile */
1108 case 'R': /* --retry <schedule>|<timeout> */
1109 schedule_str = optarg;
1111 case 'd': /* --chdir /new/dir */
1115 /* Message printed by getopt. */
1120 if (pid_str != NULL) {
1121 if (parse_pid(pid_str, &match_pid) != 0)
1122 badusage("pid value must be a number greater than 0");
1125 if (ppid_str != NULL) {
1126 if (parse_pid(ppid_str, &match_ppid) != 0)
1127 badusage("ppid value must be a number greater than 0");
1130 if (signal_str != NULL) {
1131 if (parse_signal(signal_str, &signal_nr) != 0)
1132 badusage("signal value must be numeric or name"
1133 " of signal (KILL, INT, ...)");
1136 if (schedule_str != NULL) {
1137 parse_schedule(schedule_str);
1140 if (proc_schedule_str != NULL)
1141 parse_proc_schedule(proc_schedule_str);
1143 if (io_schedule_str != NULL)
1144 parse_io_schedule(io_schedule_str);
1146 if (umask_str != NULL) {
1147 if (parse_umask(umask_str, &umask_value) != 0)
1148 badusage("umask value must be a positive number");
1151 if (action == ACTION_NONE)
1152 badusage("need one of --start or --stop or --status");
1154 if (!execname && !pid_str && !ppid_str && !pidfile && !userspec &&
1156 badusage("need at least one of --exec, --pid, --ppid, --pidfile, --user or --name");
1158 #ifdef PROCESS_NAME_SIZE
1159 if (cmdname && strlen(cmdname) > PROCESS_NAME_SIZE)
1160 warning("this system is not able to track process names\n"
1161 "longer than %d characters, please use --exec "
1162 "instead of --name.\n", PROCESS_NAME_SIZE);
1168 if (action == ACTION_START && !startas)
1169 badusage("--start needs --exec or --startas");
1171 if (mpidfile && pidfile == NULL)
1172 badusage("--make-pidfile requires --pidfile");
1173 if (rpidfile && pidfile == NULL)
1174 badusage("--remove-pidfile requires --pidfile");
1176 if (pid_str && pidfile)
1177 badusage("need either --pid of --pidfile, not both");
1179 if (background && action != ACTION_START)
1180 badusage("--background is only relevant with --start");
1182 if (!close_io && !background)
1183 badusage("--no-close is only relevant with --background");
1192 /* If it's a relative path, normalize it. */
1193 if (execname[0] != '/')
1194 execname = newpath(changedir, execname);
1197 fullexecname = newpath(changeroot, execname);
1199 fullexecname = execname;
1201 if (stat(fullexecname, &exec_stat))
1202 fatal("unable to stat %s", fullexecname);
1204 if (fullexecname != execname)
1208 if (userspec && parse_unsigned(userspec, 10, &user_id) < 0) {
1211 pw = getpwnam(userspec);
1213 fatal("user '%s' not found", userspec);
1215 user_id = pw->pw_uid;
1218 if (changegroup && parse_unsigned(changegroup, 10, &runas_gid) < 0) {
1221 gr = getgrnam(changegroup);
1223 fatal("group '%s' not found", changegroup);
1224 changegroup = gr->gr_name;
1225 runas_gid = gr->gr_gid;
1231 if (parse_unsigned(changeuser, 10, &runas_uid) == 0)
1232 pw = getpwuid(runas_uid);
1234 pw = getpwnam(changeuser);
1236 fatal("user '%s' not found", changeuser);
1237 changeuser = pw->pw_name;
1238 runas_uid = pw->pw_uid;
1239 if (changegroup == NULL) {
1240 /* Pass the default group of this user. */
1241 changegroup = ""; /* Just empty. */
1242 runas_gid = pw->pw_gid;
1244 if (stat(pw->pw_dir, &st) == 0)
1245 setenv("HOME", pw->pw_dir, 1);
1249 #if defined(OS_Linux)
1251 proc_status_field(pid_t pid, const char *field)
1253 static char *line = NULL;
1254 static size_t line_size = 0;
1260 size_t field_len = strlen(field);
1262 sprintf(filename, "/proc/%d/status", pid);
1263 fp = fopen(filename, "r");
1266 while ((line_len = getline(&line, &line_size, fp)) >= 0) {
1267 if (strncasecmp(line, field, field_len) == 0) {
1268 line[line_len - 1] = '\0';
1270 value = line + field_len;
1271 while (isspace(*value))
1281 #elif defined(OS_AIX)
1283 proc_get_psinfo(pid_t pid, struct psinfo *psinfo)
1288 sprintf(filename, "/proc/%d/psinfo", pid);
1289 fp = fopen(filename, "r");
1292 if (fread(psinfo, sizeof(*psinfo), 1, fp) == 0)
1299 #elif defined(OS_Hurd)
1303 struct ps_context *context;
1306 err = ps_context_create(getproc(), &context);
1308 error(1, err, "ps_context_create");
1310 err = proc_stat_list_create(context, &procset);
1312 error(1, err, "proc_stat_list_create");
1314 err = proc_stat_list_add_all(procset, 0, 0);
1316 error(1, err, "proc_stat_list_add_all");
1319 static struct proc_stat *
1320 get_proc_stat(pid_t pid, ps_flags_t flags)
1322 struct proc_stat *ps;
1323 ps_flags_t wanted_flags = PSTAT_PID | flags;
1328 ps = proc_stat_list_pid_proc_stat(procset, pid);
1331 if (proc_stat_set_flags(ps, wanted_flags))
1333 if ((proc_stat_flags(ps) & wanted_flags) != wanted_flags)
1338 #elif defined(HAVE_KVM_H)
1343 char errbuf[_POSIX2_LINE_MAX];
1345 kd = kvm_openfiles(NULL, KVM_MEMFILE, NULL, O_RDONLY, errbuf);
1347 errx(1, "%s", errbuf);
1352 static struct kinfo_proc *
1353 ssd_kvm_get_procs(kvm_t *kd, int op, int arg, int *count)
1355 struct kinfo_proc *kp;
1362 #if defined(OS_OpenBSD)
1363 kp = kvm_getprocs(kd, op, arg, sizeof(*kp), count);
1365 kp = kvm_getprocs(kd, op, arg, count);
1367 if (kp == NULL && errno != ESRCH)
1368 errx(1, "%s", kvm_geterr(kd));
1374 #if defined(OS_Linux)
1376 pid_is_exec(pid_t pid, const struct stat *esb)
1379 char lcontents[_POSIX_PATH_MAX + 1];
1381 const char deleted[] = " (deleted)";
1385 sprintf(lname, "/proc/%d/exe", pid);
1386 nread = readlink(lname, lcontents, sizeof(lcontents) - 1);
1390 filename = lcontents;
1391 filename[nread] = '\0';
1393 /* OpenVZ kernels contain a bogus patch that instead of appending,
1394 * prepends the deleted marker. Workaround those. Otherwise handle
1395 * the normal appended marker. */
1396 if (strncmp(filename, deleted, strlen(deleted)) == 0)
1397 filename += strlen(deleted);
1398 else if (strcmp(filename + nread - strlen(deleted), deleted) == 0)
1399 filename[nread - strlen(deleted)] = '\0';
1401 if (stat(filename, &sb) != 0)
1404 return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
1406 #elif defined(OS_AIX)
1408 pid_is_exec(pid_t pid, const struct stat *esb)
1413 sprintf(filename, "/proc/%d/object/a.out", pid);
1415 if (stat(filename, &sb) != 0)
1418 return sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino;
1420 #elif defined(OS_Hurd)
1422 pid_is_exec(pid_t pid, const struct stat *esb)
1424 struct proc_stat *ps;
1426 const char *filename;
1428 ps = get_proc_stat(pid, PSTAT_ARGS);
1432 /* On old Hurd systems we have to use the argv[0] value, because
1433 * there is nothing better. */
1434 filename = proc_stat_args(ps);
1436 /* On new Hurd systems we can use the correct value, as long
1437 * as it's not NULL nor empty, as it was the case on the first
1438 * implementation. */
1439 if (proc_stat_set_flags(ps, PSTAT_EXE) == 0 &&
1440 proc_stat_flags(ps) & PSTAT_EXE &&
1441 proc_stat_exe(ps) != NULL &&
1442 proc_stat_exe(ps)[0] != '\0')
1443 filename = proc_stat_exe(ps);
1446 if (stat(filename, &sb) != 0)
1449 return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
1451 #elif defined(OS_Darwin)
1453 pid_is_exec(pid_t pid, const struct stat *esb)
1456 char pathname[_POSIX_PATH_MAX];
1458 if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
1461 if (stat(pathname, &sb) != 0)
1464 return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
1466 #elif defined(OS_HPUX)
1468 pid_is_exec(pid_t pid, const struct stat *esb)
1470 struct pst_status pst;
1472 if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
1474 return ((dev_t)pst.pst_text.psf_fsid.psfs_id == esb->st_dev &&
1475 (ino_t)pst.pst_text.psf_fileid == esb->st_ino);
1477 #elif defined(OS_FreeBSD)
1479 pid_is_exec(pid_t pid, const struct stat *esb)
1484 char pathname[PATH_MAX];
1488 mib[2] = KERN_PROC_PATHNAME;
1490 len = sizeof(pathname);
1492 error = sysctl(mib, 4, pathname, &len, NULL, 0);
1493 if (error != 0 && errno != ESRCH)
1498 if (stat(pathname, &sb) != 0)
1501 return (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
1503 #elif defined(HAVE_KVM_H)
1505 pid_is_exec(pid_t pid, const struct stat *esb)
1509 struct kinfo_proc *kp;
1511 char buf[_POSIX2_LINE_MAX];
1513 char *start_argv_0_p, *end_argv_0_p;
1516 kd = ssd_kvm_open();
1517 kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
1521 pid_argv_p = kvm_getargv(kd, kp, argv_len);
1522 if (pid_argv_p == NULL)
1523 errx(1, "%s", kvm_geterr(kd));
1525 /* Find and compare string. */
1526 start_argv_0_p = *pid_argv_p;
1528 /* Find end of argv[0] then copy and cut of str there. */
1529 end_argv_0_p = strchr(*pid_argv_p, ' ');
1530 if (end_argv_0_p == NULL)
1531 /* There seems to be no space, so we have the command
1532 * already in its desired form. */
1533 start_argv_0_p = *pid_argv_p;
1535 /* Tests indicate that this never happens, since
1536 * kvm_getargv itself cuts of tailing stuff. This is
1537 * not what the manpage says, however. */
1538 strncpy(buf, *pid_argv_p, (end_argv_0_p - start_argv_0_p));
1539 buf[(end_argv_0_p - start_argv_0_p) + 1] = '\0';
1540 start_argv_0_p = buf;
1543 if (stat(start_argv_0_p, &sb) != 0)
1546 res = (sb.st_dev == esb->st_dev && sb.st_ino == esb->st_ino);
1555 #if defined(OS_Linux)
1557 pid_is_child(pid_t pid, pid_t ppid)
1559 const char *ppid_str;
1563 ppid_str = proc_status_field(pid, "PPid:");
1564 if (ppid_str == NULL)
1567 rc = parse_pid(ppid_str, &proc_ppid);
1571 return proc_ppid == ppid;
1573 #elif defined(OS_Hurd)
1575 pid_is_child(pid_t pid, pid_t ppid)
1577 struct proc_stat *ps;
1578 struct procinfo *pi;
1580 ps = get_proc_stat(pid, PSTAT_PROC_INFO);
1584 pi = proc_stat_proc_info(ps);
1586 return pi->ppid == ppid;
1588 #elif defined(OS_Darwin)
1590 pid_is_child(pid_t pid, pid_t ppid)
1592 struct proc_bsdinfo info;
1594 if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
1597 return (pid_t)info.pbi_ppid == ppid;
1599 #elif defined(OS_AIX)
1601 pid_is_child(pid_t pid, pid_t ppid)
1605 if (!proc_get_psinfo(pid, &psi))
1608 return (pid_t)psi.pr_ppid == ppid;
1610 #elif defined(OS_HPUX)
1612 pid_is_child(pid_t pid, pid_t ppid)
1614 struct pst_status pst;
1616 if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
1619 return pst.pst_ppid == ppid;
1621 #elif defined(OS_FreeBSD)
1623 pid_is_child(pid_t pid, pid_t ppid)
1625 struct kinfo_proc kp;
1631 mib[2] = KERN_PROC_PID;
1635 rc = sysctl(mib, 4, &kp, &len, NULL, 0);
1636 if (rc != 0 && errno != ESRCH)
1638 if (len == 0 || len != sizeof(kp))
1641 return kp.ki_ppid == ppid;
1643 #elif defined(HAVE_KVM_H)
1645 pid_is_child(pid_t pid, pid_t ppid)
1648 struct kinfo_proc *kp;
1652 kd = ssd_kvm_open();
1653 kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
1657 #if defined(OS_FreeBSD)
1658 proc_ppid = kp->ki_ppid;
1659 #elif defined(OS_OpenBSD)
1660 proc_ppid = kp->p_ppid;
1661 #elif defined(OS_DragonFlyBSD)
1662 proc_ppid = kp->kp_ppid;
1664 proc_ppid = kp->kp_proc.p_ppid;
1667 res = (proc_ppid == ppid);
1676 #if defined(OS_Linux)
1678 pid_is_user(pid_t pid, uid_t uid)
1683 sprintf(buf, "/proc/%d", pid);
1684 if (stat(buf, &sb) != 0)
1686 return (sb.st_uid == uid);
1688 #elif defined(OS_Hurd)
1690 pid_is_user(pid_t pid, uid_t uid)
1692 struct proc_stat *ps;
1694 ps = get_proc_stat(pid, PSTAT_OWNER_UID);
1695 return ps && (uid_t)proc_stat_owner_uid(ps) == uid;
1697 #elif defined(OS_Darwin)
1699 pid_is_user(pid_t pid, uid_t uid)
1701 struct proc_bsdinfo info;
1703 if (proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, sizeof(info)) < 0)
1706 return info.pbi_ruid == uid;
1708 #elif defined(OS_AIX)
1710 pid_is_user(pid_t pid, uid_t uid)
1714 if (!proc_get_psinfo(pid, &psi))
1717 return psi.pr_uid == uid;
1719 #elif defined(OS_HPUX)
1721 pid_is_user(pid_t pid, uid_t uid)
1723 struct pst_status pst;
1725 if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
1727 return ((uid_t)pst.pst_uid == uid);
1729 #elif defined(OS_FreeBSD)
1731 pid_is_user(pid_t pid, uid_t uid)
1733 struct kinfo_proc kp;
1739 mib[2] = KERN_PROC_PID;
1743 rc = sysctl(mib, 4, &kp, &len, NULL, 0);
1744 if (rc != 0 && errno != ESRCH)
1746 if (len == 0 || len != sizeof(kp))
1749 return kp.ki_ruid == uid;
1751 #elif defined(HAVE_KVM_H)
1753 pid_is_user(pid_t pid, uid_t uid)
1757 struct kinfo_proc *kp;
1760 kd = ssd_kvm_open();
1761 kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
1765 #if defined(OS_FreeBSD)
1766 proc_uid = kp->ki_ruid;
1767 #elif defined(OS_OpenBSD)
1768 proc_uid = kp->p_ruid;
1769 #elif defined(OS_DragonFlyBSD)
1770 proc_uid = kp->kp_ruid;
1771 #elif defined(OS_NetBSD)
1772 proc_uid = kp->kp_eproc.e_pcred.p_ruid;
1774 if (kp->kp_proc.p_cred)
1775 kvm_read(kd, (u_long)&(kp->kp_proc.p_cred->p_ruid),
1776 &proc_uid, sizeof(uid_t));
1781 res = (proc_uid == (uid_t)uid);
1790 #if defined(OS_Linux)
1792 pid_is_cmd(pid_t pid, const char *name)
1796 comm = proc_status_field(pid, "Name:");
1800 return strcmp(comm, name) == 0;
1802 #elif defined(OS_Hurd)
1804 pid_is_cmd(pid_t pid, const char *name)
1806 struct proc_stat *ps;
1809 const char *binary_name;
1811 ps = get_proc_stat(pid, PSTAT_ARGS);
1815 argv0 = proc_stat_args(ps);
1816 argv0_len = strlen(argv0) + 1;
1818 binary_name = basename(argv0);
1819 if (strcmp(binary_name, name) == 0)
1822 /* XXX: This is all kinds of ugly, but on the Hurd there's no way to
1823 * know the command name of a process, so we have to try to match
1824 * also on argv[1] for the case of an interpreted script. */
1825 if (proc_stat_args_len(ps) > argv0_len) {
1826 const char *script_name = basename(argv0 + argv0_len);
1828 return strcmp(script_name, name) == 0;
1833 #elif defined(OS_AIX)
1835 pid_is_cmd(pid_t pid, const char *name)
1839 if (!proc_get_psinfo(pid, &psi))
1842 return strcmp(psi.pr_fname, name) == 0;
1844 #elif defined(OS_HPUX)
1846 pid_is_cmd(pid_t pid, const char *name)
1848 struct pst_status pst;
1850 if (pstat_getproc(&pst, sizeof(pst), (size_t)0, (int)pid) < 0)
1852 return (strcmp(pst.pst_ucomm, name) == 0);
1854 #elif defined(OS_Darwin)
1856 pid_is_cmd(pid_t pid, const char *name)
1858 char pathname[_POSIX_PATH_MAX];
1860 if (proc_pidpath(pid, pathname, sizeof(pathname)) < 0)
1863 return strcmp(pathname, name) == 0;
1865 #elif defined(OS_FreeBSD)
1867 pid_is_cmd(pid_t pid, const char *name)
1869 struct kinfo_proc kp;
1875 mib[2] = KERN_PROC_PID;
1879 rc = sysctl(mib, 4, &kp, &len, NULL, 0);
1880 if (rc != 0 && errno != ESRCH)
1882 if (len == 0 || len != sizeof(kp))
1885 return strcmp(kp.ki_comm, name) == 0;
1887 #elif defined(HAVE_KVM_H)
1889 pid_is_cmd(pid_t pid, const char *name)
1892 struct kinfo_proc *kp;
1896 kd = ssd_kvm_open();
1897 kp = ssd_kvm_get_procs(kd, KERN_PROC_PID, pid, NULL);
1901 #if defined(OS_FreeBSD)
1902 process_name = kp->ki_comm;
1903 #elif defined(OS_OpenBSD)
1904 process_name = kp->p_comm;
1905 #elif defined(OS_DragonFlyBSD)
1906 process_name = kp->kp_comm;
1908 process_name = kp->kp_proc.p_comm;
1911 res = (strcmp(name, process_name) == 0);
1920 #if defined(OS_Hurd)
1922 pid_is_running(pid_t pid)
1924 return get_proc_stat(pid, 0) != NULL;
1926 #else /* !OS_Hurd */
1928 pid_is_running(pid_t pid)
1930 if (kill(pid, 0) == 0 || errno == EPERM)
1932 else if (errno == ESRCH)
1935 fatal("error checking pid %u status", pid);
1939 static enum status_code
1940 pid_check(pid_t pid)
1942 if (execname && !pid_is_exec(pid, &exec_stat))
1944 if (match_ppid > 0 && !pid_is_child(pid, match_ppid))
1946 if (userspec && !pid_is_user(pid, user_id))
1948 if (cmdname && !pid_is_cmd(pid, cmdname))
1950 if (action != ACTION_STOP && !pid_is_running(pid))
1953 pid_list_push(&found, pid);
1958 static enum status_code
1959 do_pidfile(const char *name)
1962 static pid_t pid = 0;
1965 return pid_check(pid);
1967 f = fopen(name, "r");
1969 enum status_code pid_status;
1971 if (fscanf(f, "%d", &pid) == 1)
1972 pid_status = pid_check(pid);
1974 pid_status = STATUS_UNKNOWN;
1977 if (pid_status == STATUS_DEAD)
1978 return STATUS_DEAD_PIDFILE;
1981 } else if (errno == ENOENT)
1984 fatal("unable to open pidfile %s", name);
1987 #if defined(OS_Linux) || defined(OS_Solaris) || defined(OS_AIX)
1988 static enum status_code
1992 struct dirent *entry;
1995 enum status_code prog_status = STATUS_DEAD;
1997 procdir = opendir("/proc");
1999 fatal("unable to opendir /proc");
2002 while ((entry = readdir(procdir)) != NULL) {
2003 enum status_code pid_status;
2005 if (sscanf(entry->d_name, "%d", &pid) != 1)
2009 pid_status = pid_check(pid);
2010 if (pid_status < prog_status)
2011 prog_status = pid_status;
2015 fatal("nothing in /proc - not mounted?");
2019 #elif defined(OS_Hurd)
2021 check_proc_stat(struct proc_stat *ps)
2023 pid_check(proc_stat_pid(ps));
2027 static enum status_code
2033 proc_stat_list_for_each(procset, check_proc_stat);
2040 #elif defined(OS_Darwin)
2041 static enum status_code
2045 int i, npids, pid_bufsize;
2046 enum status_code prog_status = STATUS_DEAD;
2048 npids = proc_listallpids(NULL, 0);
2050 return STATUS_UNKNOWN;
2052 /* Try to avoid sudden changes in number of PIDs. */
2054 pid_bufsize = sizeof(pid_t) * npids;
2055 pid_buf = xmalloc(pid_bufsize);
2057 npids = proc_listallpids(pid_buf, pid_bufsize);
2059 return STATUS_UNKNOWN;
2061 for (i = 0; i < npids; i++) {
2062 enum status_code pid_status;
2064 pid_status = pid_check(pid_buf[i]);
2065 if (pid_status < prog_status)
2066 prog_status = pid_status;
2073 #elif defined(OS_HPUX)
2074 static enum status_code
2077 struct pst_status pst[10];
2080 enum status_code prog_status = STATUS_DEAD;
2082 while ((count = pstat_getproc(pst, sizeof(pst[0]), 10, idx)) > 0) {
2083 enum status_code pid_status;
2085 for (i = 0; i < count; i++) {
2086 pid_status = pid_check(pst[i].pst_pid);
2087 if (pid_status < prog_status)
2088 prog_status = pid_status;
2090 idx = pst[count - 1].pst_idx + 1;
2095 #elif defined(OS_FreeBSD)
2096 static enum status_code
2099 struct kinfo_proc *kp;
2103 enum status_code prog_status = STATUS_DEAD;
2107 mib[2] = KERN_PROC_PROC;
2109 rc = sysctl(mib, 3, NULL, &len, NULL, 0);
2110 if (rc != 0 && errno != ESRCH)
2111 return STATUS_UNKNOWN;
2113 return STATUS_UNKNOWN;
2116 rc = sysctl(mib, 3, kp, &len, NULL, 0);
2117 if (rc != 0 && errno != ESRCH)
2118 return STATUS_UNKNOWN;
2120 return STATUS_UNKNOWN;
2121 nentries = len / sizeof(*kp);
2123 for (i = 0; i < nentries; i++) {
2124 enum status_code pid_status;
2126 pid_status = pid_check(kp[i].ki_pid);
2127 if (pid_status < prog_status)
2128 prog_status = pid_status;
2135 #elif defined(HAVE_KVM_H)
2136 static enum status_code
2141 struct kinfo_proc *kp;
2142 enum status_code prog_status = STATUS_DEAD;
2144 kd = ssd_kvm_open();
2145 kp = ssd_kvm_get_procs(kd, KERN_PROC_ALL, 0, &nentries);
2147 for (i = 0; i < nentries; i++) {
2148 enum status_code pid_status;
2151 #if defined(OS_FreeBSD)
2153 #elif defined(OS_OpenBSD)
2155 #elif defined(OS_DragonFlyBSD)
2158 pid = kp[i].kp_proc.p_pid;
2161 pid_status = pid_check(pid);
2162 if (pid_status < prog_status)
2163 prog_status = pid_status;
2172 static enum status_code
2175 pid_list_free(&found);
2178 return pid_check(match_pid);
2180 return do_pidfile(pidfile);
2182 return do_procinit();
2186 do_start(int argc, char **argv)
2188 int devnull_fd = -1;
2196 printf("%s already running.\n", execname ? execname : "process");
2199 if (testmode && quietmode <= 0) {
2200 printf("Would start %s ", startas);
2202 printf("%s ", *argv++);
2203 if (changeuser != NULL) {
2204 printf(" (as user %s[%d]", changeuser, runas_uid);
2205 if (changegroup != NULL)
2206 printf(", and group %s[%d])", changegroup, runas_gid);
2210 if (changeroot != NULL)
2211 printf(" in directory %s", changeroot);
2213 printf(", and add %i to the priority", nicelevel);
2215 printf(", with scheduling policy %s with priority %i",
2216 proc_sched->policy_name, proc_sched->priority);
2218 printf(", with IO scheduling class %s with priority %i",
2219 io_sched->policy_name, io_sched->priority);
2225 printf("Starting %s...\n", startas);
2228 /* Ok, we need to detach this process. */
2230 else if (mpidfile && pidfile != NULL)
2231 /* User wants _us_ to make the pidfile, but detach themself! */
2232 write_pidfile(pidfile, getpid());
2233 if (background && close_io) {
2234 devnull_fd = open("/dev/null", O_RDWR);
2236 fatal("unable to open '%s'", "/dev/null");
2240 if ((nice(nicelevel) == -1) && (errno != 0))
2241 fatal("unable to alter nice level by %i", nicelevel);
2244 set_proc_schedule(proc_sched);
2246 set_io_schedule(io_sched);
2247 if (umask_value >= 0)
2249 if (changeroot != NULL) {
2250 if (chdir(changeroot) < 0)
2251 fatal("unable to chdir() to %s", changeroot);
2252 if (chroot(changeroot) < 0)
2253 fatal("unable to chroot() to %s", changeroot);
2255 if (chdir(changedir) < 0)
2256 fatal("unable to chdir() to %s", changedir);
2260 if (changegroup != NULL) {
2261 if (rgid != (gid_t)runas_gid)
2262 if (setgid(runas_gid))
2263 fatal("unable to set gid to %d", runas_gid);
2265 if (changeuser != NULL) {
2266 /* We assume that if our real user and group are the same as
2267 * the ones we should switch to, the supplementary groups
2268 * will be already in place. */
2269 if (rgid != (gid_t)runas_gid || ruid != (uid_t)runas_uid)
2270 if (initgroups(changeuser, runas_gid))
2271 fatal("unable to set initgroups() with gid %d",
2274 if (ruid != (uid_t)runas_uid)
2275 if (setuid(runas_uid))
2276 fatal("unable to set uid to %s", changeuser);
2279 if (background && close_io) {
2282 dup2(devnull_fd, 0); /* stdin */
2283 dup2(devnull_fd, 1); /* stdout */
2284 dup2(devnull_fd, 2); /* stderr */
2286 /* Now close all extra fds. */
2287 for (i = get_open_fd_max() - 1; i >= 3; --i)
2290 execv(startas, argv);
2291 fatal("unable to start %s", startas);
2295 do_stop(int sig_num, int *n_killed, int *n_notkilled)
2307 pid_list_free(&killed);
2309 for (p = found; p; p = p->next) {
2312 printf("Would send signal %d to %d.\n",
2315 } else if (kill(p->pid, sig_num) == 0) {
2316 pid_list_push(&killed, p->pid);
2320 warning("failed to kill %d: %s\n",
2321 p->pid, strerror(errno));
2328 do_stop_summary(int retry_nr)
2332 if (quietmode >= 0 || !killed)
2335 printf("Stopped %s (pid", what_stop);
2336 for (p = killed; p; p = p->next)
2337 printf(" %d", p->pid);
2340 printf(", retry #%d", retry_nr);
2344 static void DPKG_ATTR_PRINTF(1)
2345 set_what_stop(const char *format, ...)
2350 va_start(arglist, format);
2351 rc = vasprintf(&what_stop, format, arglist);
2355 fatal("cannot allocate formatted string");
2359 * We want to keep polling for the processes, to see if they've exited, or
2360 * until the timeout expires.
2362 * This is a somewhat complicated algorithm to try to ensure that we notice
2363 * reasonably quickly when all the processes have exited, but don't spend
2364 * too much CPU time polling. In particular, on a fast machine with
2365 * quick-exiting daemons we don't want to delay system shutdown too much,
2366 * whereas on a slow one, or where processes are taking some time to exit,
2367 * we want to increase the polling interval.
2369 * The algorithm is as follows: we measure the elapsed time it takes to do
2370 * one poll(), and wait a multiple of this time for the next poll. However,
2371 * if that would put us past the end of the timeout period we wait only as
2372 * long as the timeout period, but in any case we always wait at least
2373 * MIN_POLL_INTERVAL (20ms). The multiple (‘ratio’) starts out as 2, and
2374 * increases by 1 for each poll to a maximum of 10; so we use up to between
2375 * 30% and 10% of the machine's resources (assuming a few reasonable things
2376 * about system performance).
2379 do_stop_timeout(int timeout, int *n_killed, int *n_notkilled)
2381 struct timespec stopat, before, after, interval, maxinterval;
2384 timespec_gettime(&stopat);
2385 stopat.tv_sec += timeout;
2388 timespec_gettime(&before);
2389 if (timespec_cmp(&before, &stopat, >))
2392 do_stop(0, n_killed, n_notkilled);
2396 timespec_gettime(&after);
2398 if (!timespec_cmp(&after, &stopat, <))
2404 timespec_sub(&stopat, &after, &maxinterval);
2405 timespec_sub(&after, &before, &interval);
2406 timespec_mul(&interval, ratio);
2408 if (interval.tv_sec < 0 || interval.tv_nsec < 0)
2409 interval.tv_sec = interval.tv_nsec = 0;
2411 if (timespec_cmp(&interval, &maxinterval, >))
2412 interval = maxinterval;
2414 if (interval.tv_sec == 0 &&
2415 interval.tv_nsec <= MIN_POLL_INTERVAL)
2416 interval.tv_nsec = MIN_POLL_INTERVAL;
2418 rc = pselect(0, NULL, NULL, NULL, &interval, NULL);
2419 if (rc < 0 && errno != EINTR)
2420 fatal("select() failed for pause");
2425 finish_stop_schedule(bool anykilled)
2427 if (rpidfile && pidfile && !testmode)
2428 remove_pidfile(pidfile);
2434 printf("No %s found running; none killed.\n", what_stop);
2440 run_stop_schedule(void)
2442 int position, n_killed, n_notkilled, value, retry_nr;
2446 if (schedule != NULL) {
2448 printf("Ignoring --retry in test mode\n");
2454 set_what_stop("%s", cmdname);
2456 set_what_stop("%s", execname);
2458 set_what_stop("process in pidfile '%s'", pidfile);
2459 else if (match_pid > 0)
2460 set_what_stop("process with pid %d", match_pid);
2461 else if (match_ppid > 0)
2462 set_what_stop("process(es) with parent pid %d", match_ppid);
2464 set_what_stop("process(es) owned by '%s'", userspec);
2466 fatal("internal error, no match option, please report");
2471 if (schedule == NULL) {
2472 do_stop(signal_nr, &n_killed, &n_notkilled);
2474 if (n_notkilled > 0 && quietmode <= 0)
2475 printf("%d pids were not killed\n", n_notkilled);
2478 return finish_stop_schedule(anykilled);
2481 for (position = 0; position < schedule_length; position++) {
2483 value = schedule[position].value;
2486 switch (schedule[position].type) {
2491 do_stop(value, &n_killed, &n_notkilled);
2492 do_stop_summary(retry_nr++);
2494 return finish_stop_schedule(anykilled);
2499 if (do_stop_timeout(value, &n_killed, &n_notkilled))
2500 return finish_stop_schedule(anykilled);
2504 assert(!"schedule[].type value must be valid");
2509 printf("Program %s, %d process(es), refused to die.\n",
2510 what_stop, n_killed);
2516 main(int argc, char **argv)
2520 parse_options(argc, argv);
2526 if (action == ACTION_START)
2527 return do_start(argc, argv);
2528 else if (action == ACTION_STOP)
2529 return run_stop_schedule();
2530 else if (action == ACTION_STATUS)
2531 return do_findprocs();