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 fork_before_exec = 0;
26 static int signal_nr = 15;
27 static int user_id = -1;
28 static const char *userspec = NULL;
29 static const char *cmdname = NULL;
30 static char *execname = NULL;
31 static char *startas = NULL;
33 typedef struct pid_list {
34 struct pid_list *next;
38 static pid_list *found = NULL;
45 p = xmalloc(sizeof(*p));
53 parse_options(int argc, char * const *argv)
59 c = getopt (argc, argv, "a:n:s:u:x:KSb");
76 if (sscanf(optarg, "%d", &signal_nr) != 1)
77 error_msg_and_die ("-s takes a numeric argument");
94 error_msg_and_die ("need one of -S or -K");
96 if (!execname && !userspec)
97 error_msg_and_die ("need at least one of -x or -u");
102 if (start && !startas)
103 error_msg_and_die ("-S needs -x or -a");
108 pid_is_exec(int pid, const char *exec)
113 sprintf(buf, "/proc/%d/cmdline", pid);
114 fp = fopen(buf, "r");
115 if (fp && fgets (buf, sizeof (buf), fp) ) {
116 if (strncmp (buf, exec, strlen(exec)) == 0)
124 pid_is_user(int pid, int uid)
129 sprintf(buf, "/proc/%d", pid);
130 if (stat(buf, &sb) != 0)
132 return (sb.st_uid == uid);
137 pid_is_cmd(int pid, const char *name)
143 sprintf(buf, "/proc/%d/stat", pid);
147 while ((c = getc(f)) != EOF && c != '(')
153 /* this hopefully handles command names containing ')' */
154 while ((c = getc(f)) != EOF && c == *name)
157 return (c == ')' && *name == '\0');
164 if (execname && !pid_is_exec(pid, execname)) {
167 if (userspec && !pid_is_user(pid, user_id)) {
170 if (cmdname && !pid_is_cmd(pid, cmdname)) {
182 struct dirent *entry;
185 procdir = opendir("/proc");
187 perror_msg_and_die ("opendir /proc");
190 while ((entry = readdir(procdir)) != NULL) {
191 if (sscanf(entry->d_name, "%d", &pid) != 1)
198 error_msg_and_die ("nothing in /proc - not mounted?");
210 strcpy(what, cmdname);
212 strcpy(what, execname);
214 sprintf(what, "process(es) owned by `%s'", userspec);
216 error_msg_and_die ("internal error, please report");
219 printf("no %s found; none killed.\n", what);
222 for (p = found; p; p = p->next) {
223 if (kill(p->pid, signal_nr) == 0) {
227 perror_msg("warning: failed to kill %d:", p->pid);
231 printf("stopped %s (pid", what);
232 for (p = found; p; p = p->next)
234 printf(" %d", -p->pid);
241 start_stop_daemon_main(int argc, char **argv)
243 parse_options(argc, argv);
247 if (userspec && sscanf(userspec, "%d", &user_id) != 1)
248 user_id = my_getpwnam(userspec);
258 printf("%s already running.\n%d\n", execname ,found->pid);
262 if (fork_before_exec) {
263 if (daemon(0, 0) == -1)
264 perror_msg_and_die ("unable to fork");
267 execv(startas, argv);
268 perror_msg_and_die ("unable to start %s", startas);