1 /* vi: set sw=4 ts=4: */
3 * Mini start-stop-daemon implementation(s) for busybox
5 * Written by Marek Michalkiewicz <marekm@i17linuxb.ists.pwr.wroc.pl>,
7 * Adapted for busybox David Kimdon <dwhedon@gordian.com>
25 static int signal_nr = 15;
26 static int user_id = -1;
27 static const char *userspec = NULL;
28 static const char *cmdname = NULL;
29 static char *execname = NULL;
30 static char *startas = NULL;
31 static const char *progname = "";
34 struct pid_list *next;
38 static struct pid_list *found = NULL;
39 static struct pid_list *killed = NULL;
42 push(struct pid_list **list, int pid)
46 p = xmalloc(sizeof(*p));
54 parse_options(int argc, char * const *argv)
60 c = getopt (argc, argv, "a:n:s:u:x:KS");
77 if (sscanf(optarg, "%d", &signal_nr) != 1)
78 error_msg_and_die ("-s takes a numeric argument");
93 error_msg_and_die ("need one of -S or -K");
95 if (!execname && !userspec)
96 error_msg_and_die ("need at least one of -x or -u");
101 if (start && !startas)
102 error_msg_and_die ("-S needs -x or -a");
107 pid_is_exec(int pid, const char *exec)
112 sprintf(buf, "/proc/%d/cmdline", pid);
113 fp = fopen(buf, "r");
114 if (fp && fgets (buf, sizeof (buf), fp) ) {
115 if (strncmp (buf, exec, strlen(exec)) == 0)
123 pid_is_user(int pid, int uid)
128 sprintf(buf, "/proc/%d", pid);
129 if (stat(buf, &sb) != 0)
131 return (sb.st_uid == uid);
136 pid_is_cmd(int pid, const char *name)
142 sprintf(buf, "/proc/%d/stat", pid);
146 while ((c = getc(f)) != EOF && c != '(')
152 /* this hopefully handles command names containing ')' */
153 while ((c = getc(f)) != EOF && c == *name)
156 return (c == ')' && *name == '\0');
163 if (execname && !pid_is_exec(pid, execname)) {
166 if (userspec && !pid_is_user(pid, user_id)) {
169 if (cmdname && !pid_is_cmd(pid, cmdname)) {
181 struct dirent *entry;
184 procdir = opendir("/proc");
186 perror_msg_and_die ("opendir /proc");
189 while ((entry = readdir(procdir)) != NULL) {
190 if (sscanf(entry->d_name, "%d", &pid) != 1)
197 error_msg_and_die ("nothing in /proc - not mounted?");
208 strcpy(what, cmdname);
210 strcpy(what, execname);
212 sprintf(what, "process(es) owned by `%s'", userspec);
214 error_msg_and_die ("internal error, please report");
217 printf("no %s found; none killed.\n", what);
220 for (p = found; p; p = p->next) {
221 if (kill(p->pid, signal_nr) == 0)
222 push(&killed, p->pid);
224 printf("%s: warning: failed to kill %d: %s\n",
225 progname, p->pid, strerror(errno));
228 printf("stopped %s (pid", what);
229 for (p = killed; p; p = p->next)
230 printf(" %d", p->pid);
237 start_stop_daemon_main(int argc, char **argv)
241 parse_options(argc, argv);
245 if (userspec && sscanf(userspec, "%d", &user_id) != 1) {
248 pw = getpwnam(userspec);
250 error_msg_and_die ("user `%s' not found\n", userspec);
252 user_id = pw->pw_uid;
263 printf("%s already running.\n", execname);
264 printf("%d\n",found->pid);
268 execv(startas, argv);
269 perror_msg_and_die ("unable to start %s", startas);