1 /* $NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $ */
4 * Copyright (c) 2002 The NetBSD Foundation, Inc.
5 * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
8 * This code is derived from software contributed to The NetBSD Foundation
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
36 #include <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/sysctl.h>
40 #include <sys/queue.h>
63 #define STATUS_MATCH 0
64 #define STATUS_NOMATCH 1
65 #define STATUS_BADUSAGE 2
66 #define STATUS_ERROR 3
71 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
72 #define PSKIP(kp) ((kp)->ki_pid == mypid || \
73 (!kthreads && ((kp)->ki_flag & P_KTHREAD) != 0))
86 SLIST_ENTRY(list) li_chain;
90 SLIST_HEAD(listhead, list);
92 static struct kinfo_proc *plist;
93 static char *selected;
94 static const char *delim = "\n";
97 static int signum = SIGTERM;
100 static int interactive;
103 static int matchargs;
104 static int fullmatch;
106 static int cflags = REG_EXTENDED;
111 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
112 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
113 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
114 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
115 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
116 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
117 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
118 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
120 static void usage(void) __attribute__((__noreturn__));
121 static int killact(const struct kinfo_proc *);
122 static int grepact(const struct kinfo_proc *);
123 static void makelist(struct listhead *, enum listtype, char *);
124 static int takepid(const char *, int);
127 main(int argc, char **argv)
129 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
130 const char *execf, *coref;
131 int ancestors, debug_opt;
132 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
134 int (*action)(const struct kinfo_proc *);
135 struct kinfo_proc *kp;
137 struct timeval best_tval;
142 setlocale(LC_ALL, "");
144 if (strcmp(getprogname(), "pgrep") == 0) {
151 if (argc > 1 && p[0] == '-') {
153 i = (int)strtol(p, &q, 10);
159 if (strncasecmp(p, "sig", 3) == 0)
161 for (i = 1; i < NSIG; i++)
162 if (strcasecmp(sys_signame[i], p) == 0)
180 coref = _PATH_DEVNULL;
182 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ad:fg:ij:lnoqs:t:u:vx")) != -1)
192 makelist(&rgidlist, LT_GROUP, optarg);
210 makelist(&ppidlist, LT_GENERIC, optarg);
219 makelist(&ruidlist, LT_USER, optarg);
234 makelist(&pgrplist, LT_PGRP, optarg);
241 makelist(&jidlist, LT_JID, optarg);
263 makelist(&sidlist, LT_SID, optarg);
267 makelist(&tdevlist, LT_TTY, optarg);
271 makelist(&euidlist, LT_USER, optarg);
291 if (newest && oldest)
292 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
294 pidfromfile = takepid(pidfile, pidfilelock);
298 "Option -L doesn't make sense without -F");
306 * Retrieve the list of running processes from the kernel.
308 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
310 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
313 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
314 * just want processes and not individual kernel threads.
316 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
318 errx(STATUS_ERROR, "Cannot get process list (%s)",
323 * Allocate memory which will be used to keep track of the
326 if ((selected = malloc(nproc)) == NULL) {
327 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
330 memset(selected, 0, nproc);
333 * Refine the selection.
335 for (; *argv != NULL; argv++) {
336 if ((rv = regcomp(®, *argv, cflags)) != 0) {
337 regerror(rv, ®, buf, sizeof(buf));
338 errx(STATUS_BADUSAGE,
339 "Cannot compile regular expression `%s' (%s)",
343 for (i = 0, kp = plist; i < nproc; i++, kp++) {
346 fprintf(stderr, "* Skipped %5d %3d %s\n",
347 kp->ki_pid, kp->ki_uid, kp->ki_comm);
352 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
354 while (jsz < sizeof(buf) && *pargv != NULL) {
355 jsz += snprintf(buf + jsz,
357 pargv[1] != NULL ? "%s " : "%s",
365 rv = regexec(®, mstr, 1, ®match, 0);
368 if (regmatch.rm_so == 0 &&
374 } else if (rv != REG_NOMATCH) {
375 regerror(rv, ®, buf, sizeof(buf));
377 "Regular expression evaluation error (%s)",
381 const char *rv_res = "NoMatch";
384 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
385 kp->ki_pid, kp->ki_uid, mstr);
392 for (i = 0, kp = plist; i < nproc; i++, kp++) {
396 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
401 SLIST_FOREACH(li, &ruidlist, li_chain)
402 if (kp->ki_ruid == (uid_t)li->li_number)
404 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
409 SLIST_FOREACH(li, &rgidlist, li_chain)
410 if (kp->ki_rgid == (gid_t)li->li_number)
412 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
417 SLIST_FOREACH(li, &euidlist, li_chain)
418 if (kp->ki_uid == (uid_t)li->li_number)
420 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
425 SLIST_FOREACH(li, &ppidlist, li_chain)
426 if (kp->ki_ppid == (pid_t)li->li_number)
428 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
433 SLIST_FOREACH(li, &pgrplist, li_chain)
434 if (kp->ki_pgid == (pid_t)li->li_number)
436 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
441 SLIST_FOREACH(li, &tdevlist, li_chain) {
442 if (li->li_number == -1 &&
443 (kp->ki_flag & P_CONTROLT) == 0)
445 if (kp->ki_tdev == (dev_t)li->li_number)
448 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
453 SLIST_FOREACH(li, &sidlist, li_chain)
454 if (kp->ki_sid == (pid_t)li->li_number)
456 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
461 SLIST_FOREACH(li, &jidlist, li_chain) {
462 /* A particular jail ID, including 0 (not in jail) */
463 if (kp->ki_jid == (int)li->li_number)
466 if (kp->ki_jid > 0 && li->li_number == -1)
469 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
481 for (i = 0, kp = plist; i < nproc; i++, kp++) {
484 if (kp->ki_pid == pid) {
494 break; /* Maybe we're in a jail ? */
499 if (newest || oldest) {
500 best_tval.tv_sec = 0;
501 best_tval.tv_usec = 0;
504 for (i = 0, kp = plist; i < nproc; i++, kp++) {
508 /* The first entry of the list which matched. */
510 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
511 /* This entry is newer than previous "best". */
512 if (oldest) /* but we want the oldest */
515 /* This entry is older than previous "best". */
516 if (newest) /* but we want the newest */
519 /* This entry is better than previous "best" entry. */
520 best_tval.tv_sec = kp->ki_start.tv_sec;
521 best_tval.tv_usec = kp->ki_start.tv_usec;
525 memset(selected, 0, nproc);
527 selected[bestidx] = 1;
531 * Take the appropriate action for each matched process, if any.
533 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
544 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
553 ustr = "[-LSfilnoqvx] [-d delim]";
555 ustr = "[-signal] [-ILfinovx]";
558 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
559 " [-P ppid] [-U uid] [-g pgrp] [-j jid] [-s sid]\n"
560 " [-t tty] [-u euid] pattern ...\n", getprogname(),
563 exit(STATUS_BADUSAGE);
567 show_process(const struct kinfo_proc *kp)
575 if ((longfmt || !pgrep) && matchargs &&
576 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
577 printf("%d ", (int)kp->ki_pid);
578 for (; *argv != NULL; argv++) {
583 } else if (longfmt || !pgrep)
584 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
586 printf("%d", (int)kp->ki_pid);
590 killact(const struct kinfo_proc *kp)
596 * Be careful, ask before killing.
602 first = ch = getchar();
603 while (ch != '\n' && ch != EOF)
605 if (first != 'y' && first != 'Y')
608 if (kill(kp->ki_pid, signum) == -1) {
610 * Check for ESRCH, which indicates that the process
611 * disappeared between us matching it and us
612 * signalling it; don't issue a warning about it.
615 warn("signalling pid %d", (int)kp->ki_pid);
617 * Return 0 to indicate that the process should not be
618 * considered a match, since we didn't actually get to
627 grepact(const struct kinfo_proc *kp)
637 makelist(struct listhead *head, enum listtype type, char *src)
644 char *sp, *ep, buf[MAXPATHLEN];
649 while ((sp = strsep(&src, ",")) != NULL) {
653 if ((li = malloc(sizeof(*li))) == NULL) {
654 err(STATUS_ERROR, "Cannot allocate %zu bytes",
658 SLIST_INSERT_HEAD(head, li, li_chain);
661 li->li_number = (uid_t)strtol(sp, &ep, 0);
665 if (li->li_number == 0)
666 li->li_number = getpgrp();
669 if (li->li_number == 0)
670 li->li_number = getsid(mypid);
673 if (li->li_number < 0)
674 errx(STATUS_BADUSAGE,
675 "Negative jail ID `%s'", sp);
676 /* For compatibility with old -j */
677 if (li->li_number == 0)
678 li->li_number = -1; /* any jail */
681 if (li->li_number < 0)
682 errx(STATUS_BADUSAGE,
683 "Negative /dev/pts tty `%s'", sp);
684 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
686 if (stat(buf, &st) != -1)
689 errx(STATUS_BADUSAGE, "No such tty: `"
690 _PATH_DEV "pts/%s'", sp);
691 err(STATUS_ERROR, "Cannot access `"
692 _PATH_DEV "pts/%s'", sp);
702 if ((pw = getpwnam(sp)) == NULL)
703 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
704 li->li_number = pw->pw_uid;
707 if ((gr = getgrnam(sp)) == NULL)
708 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
709 li->li_number = gr->gr_gid;
712 if (strcmp(sp, "-") == 0) {
715 } else if (strcmp(sp, "co") == 0) {
721 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
722 if (stat(buf, &st) != -1)
725 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
726 if (stat(buf, &st) != -1)
730 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
731 err(STATUS_ERROR, "Cannot access `%s'", sp);
733 foundtty: if ((st.st_mode & S_IFCHR) == 0)
734 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
736 li->li_number = st.st_rdev;
739 if (strcmp(sp, "none") == 0)
741 else if (strcmp(sp, "any") == 0)
743 else if (*ep != '\0')
744 errx(STATUS_BADUSAGE,
745 "Invalid jail ID `%s'", sp);
757 takepid(const char *pidfile, int pidfilelock)
759 char *endp, line[BUFSIZ];
763 fh = fopen(pidfile, "r");
765 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
769 * If we can lock pidfile, this means that daemon is not
770 * running, so would be better not to kill some random process.
772 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
774 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
776 if (errno != EWOULDBLOCK) {
778 "Error while locking file '%s'", pidfile);
783 if (fgets(line, sizeof(line), fh) == NULL) {
786 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
789 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
793 rval = strtol(line, &endp, 10);
794 if (*endp != '\0' && !isspace((unsigned char)*endp))
795 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
796 else if (rval < MIN_PID || rval > MAX_PID)
797 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);