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>
64 #define STATUS_MATCH 0
65 #define STATUS_NOMATCH 1
66 #define STATUS_BADUSAGE 2
67 #define STATUS_ERROR 3
72 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
73 #define PSKIP(kp) ((kp)->ki_pid == mypid || \
74 (!kthreads && ((kp)->ki_flag & P_KTHREAD) != 0))
88 SLIST_ENTRY(list) li_chain;
93 SLIST_HEAD(listhead, list);
95 static struct kinfo_proc *plist;
96 static char *selected;
97 static const char *delim = "\n";
100 static int signum = SIGTERM;
103 static int interactive;
106 static int matchargs;
107 static int fullmatch;
109 static int cflags = REG_EXTENDED;
114 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
115 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
116 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
117 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
118 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
119 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
120 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
121 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
122 static struct listhead classlist = SLIST_HEAD_INITIALIZER(classlist);
124 static void usage(void) __attribute__((__noreturn__));
125 static int killact(const struct kinfo_proc *);
126 static int grepact(const struct kinfo_proc *);
127 static void makelist(struct listhead *, enum listtype, char *);
128 static int takepid(const char *, int);
131 main(int argc, char **argv)
133 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
134 const char *execf, *coref;
135 int ancestors, debug_opt, did_action;
136 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
138 int (*action)(const struct kinfo_proc *);
139 struct kinfo_proc *kp;
141 struct timeval best_tval;
146 setlocale(LC_ALL, "");
148 if (strcmp(getprogname(), "pgrep") == 0) {
155 if (argc > 1 && p[0] == '-') {
157 i = (int)strtol(p, &q, 10);
163 if (strncasecmp(p, "SIG", 3) == 0)
165 for (i = 1; i < NSIG; i++)
166 if (strcasecmp(sys_signame[i], p) == 0)
184 coref = _PATH_DEVNULL;
186 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1)
196 makelist(&rgidlist, LT_GROUP, optarg);
214 makelist(&ppidlist, LT_GENERIC, optarg);
223 makelist(&ruidlist, LT_USER, optarg);
230 makelist(&classlist, LT_CLASS, optarg);
242 makelist(&pgrplist, LT_PGRP, optarg);
249 makelist(&jidlist, LT_JAIL, optarg);
269 makelist(&sidlist, LT_SID, optarg);
273 makelist(&tdevlist, LT_TTY, optarg);
277 makelist(&euidlist, LT_USER, optarg);
297 if (newest && oldest)
298 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
300 pidfromfile = takepid(pidfile, pidfilelock);
304 "Option -L doesn't make sense without -F");
312 * Retrieve the list of running processes from the kernel.
314 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
316 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
319 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
320 * just want processes and not individual kernel threads.
322 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
324 errx(STATUS_ERROR, "Cannot get process list (%s)",
329 * Allocate memory which will be used to keep track of the
332 if ((selected = malloc(nproc)) == NULL) {
333 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
336 memset(selected, 0, nproc);
339 * Refine the selection.
341 for (; *argv != NULL; argv++) {
342 if ((rv = regcomp(®, *argv, cflags)) != 0) {
343 regerror(rv, ®, buf, sizeof(buf));
344 errx(STATUS_BADUSAGE,
345 "Cannot compile regular expression `%s' (%s)",
349 for (i = 0, kp = plist; i < nproc; i++, kp++) {
352 fprintf(stderr, "* Skipped %5d %3d %s\n",
353 kp->ki_pid, kp->ki_uid, kp->ki_comm);
358 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
360 while (jsz < sizeof(buf) && *pargv != NULL) {
361 jsz += snprintf(buf + jsz,
363 pargv[1] != NULL ? "%s " : "%s",
371 rv = regexec(®, mstr, 1, ®match, 0);
374 if (regmatch.rm_so == 0 &&
380 } else if (rv != REG_NOMATCH) {
381 regerror(rv, ®, buf, sizeof(buf));
383 "Regular expression evaluation error (%s)",
387 const char *rv_res = "NoMatch";
390 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
391 kp->ki_pid, kp->ki_uid, mstr);
398 for (i = 0, kp = plist; i < nproc; i++, kp++) {
402 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
407 SLIST_FOREACH(li, &ruidlist, li_chain)
408 if (kp->ki_ruid == (uid_t)li->li_number)
410 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
415 SLIST_FOREACH(li, &rgidlist, li_chain)
416 if (kp->ki_rgid == (gid_t)li->li_number)
418 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
423 SLIST_FOREACH(li, &euidlist, li_chain)
424 if (kp->ki_uid == (uid_t)li->li_number)
426 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
431 SLIST_FOREACH(li, &ppidlist, li_chain)
432 if (kp->ki_ppid == (pid_t)li->li_number)
434 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
439 SLIST_FOREACH(li, &pgrplist, li_chain)
440 if (kp->ki_pgid == (pid_t)li->li_number)
442 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
447 SLIST_FOREACH(li, &tdevlist, li_chain) {
448 if (li->li_number == -1 &&
449 (kp->ki_flag & P_CONTROLT) == 0)
451 if (kp->ki_tdev == (dev_t)li->li_number)
454 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
459 SLIST_FOREACH(li, &sidlist, li_chain)
460 if (kp->ki_sid == (pid_t)li->li_number)
462 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
467 SLIST_FOREACH(li, &jidlist, li_chain) {
468 /* A particular jail ID, including 0 (not in jail) */
469 if (kp->ki_jid == (int)li->li_number)
472 if (kp->ki_jid > 0 && li->li_number == -1)
475 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
480 SLIST_FOREACH(li, &classlist, li_chain) {
482 * We skip P_SYSTEM processes to match ps(1) output.
484 if ((kp->ki_flag & P_SYSTEM) == 0 &&
485 strcmp(kp->ki_loginclass, li->li_name) == 0)
488 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
500 for (i = 0, kp = plist; i < nproc; i++, kp++) {
503 if (kp->ki_pid == pid) {
513 break; /* Maybe we're in a jail ? */
518 if (newest || oldest) {
519 best_tval.tv_sec = 0;
520 best_tval.tv_usec = 0;
523 for (i = 0, kp = plist; i < nproc; i++, kp++) {
527 /* The first entry of the list which matched. */
529 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
530 /* This entry is newer than previous "best". */
531 if (oldest) /* but we want the oldest */
534 /* This entry is older than previous "best". */
535 if (newest) /* but we want the newest */
538 /* This entry is better than previous "best" entry. */
539 best_tval.tv_sec = kp->ki_start.tv_sec;
540 best_tval.tv_usec = kp->ki_start.tv_usec;
544 memset(selected, 0, nproc);
546 selected[bestidx] = 1;
550 * Take the appropriate action for each matched process, if any.
553 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
557 if (longfmt && !pgrep) {
559 printf("kill -%d %d\n", signum, kp->ki_pid);
567 if (!did_action && !pgrep && longfmt)
569 "No matching processes belonging to you were found\n");
571 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
580 ustr = "[-LSfilnoqvx] [-d delim]";
582 ustr = "[-signal] [-ILfilnovx]";
585 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
586 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
587 " [-s sid] [-t tty] [-u euid] pattern ...\n",
588 getprogname(), ustr);
590 exit(STATUS_BADUSAGE);
594 show_process(const struct kinfo_proc *kp)
602 if ((longfmt || !pgrep) && matchargs &&
603 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
604 printf("%d ", (int)kp->ki_pid);
605 for (; *argv != NULL; argv++) {
610 } else if (longfmt || !pgrep)
611 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
613 printf("%d", (int)kp->ki_pid);
617 killact(const struct kinfo_proc *kp)
623 * Be careful, ask before killing.
629 first = ch = getchar();
630 while (ch != '\n' && ch != EOF)
632 if (first != 'y' && first != 'Y')
635 if (kill(kp->ki_pid, signum) == -1) {
637 * Check for ESRCH, which indicates that the process
638 * disappeared between us matching it and us
639 * signalling it; don't issue a warning about it.
642 warn("signalling pid %d", (int)kp->ki_pid);
644 * Return 0 to indicate that the process should not be
645 * considered a match, since we didn't actually get to
654 grepact(const struct kinfo_proc *kp)
664 makelist(struct listhead *head, enum listtype type, char *src)
671 char *sp, *ep, buf[MAXPATHLEN];
676 while ((sp = strsep(&src, ",")) != NULL) {
680 if ((li = malloc(sizeof(*li))) == NULL) {
681 err(STATUS_ERROR, "Cannot allocate %zu bytes",
685 SLIST_INSERT_HEAD(head, li, li_chain);
688 if (type != LT_CLASS)
689 li->li_number = (uid_t)strtol(sp, &ep, 0);
691 if (type != LT_CLASS && *ep == '\0') {
694 if (li->li_number == 0)
695 li->li_number = getpgrp();
698 if (li->li_number == 0)
699 li->li_number = getsid(mypid);
702 if (li->li_number < 0)
703 errx(STATUS_BADUSAGE,
704 "Negative jail ID `%s'", sp);
705 /* For compatibility with old -j */
706 if (li->li_number == 0)
707 li->li_number = -1; /* any jail */
710 if (li->li_number < 0)
711 errx(STATUS_BADUSAGE,
712 "Negative /dev/pts tty `%s'", sp);
713 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
715 if (stat(buf, &st) != -1)
718 errx(STATUS_BADUSAGE, "No such tty: `"
719 _PATH_DEV "pts/%s'", sp);
720 err(STATUS_ERROR, "Cannot access `"
721 _PATH_DEV "pts/%s'", sp);
731 if ((pw = getpwnam(sp)) == NULL)
732 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
733 li->li_number = pw->pw_uid;
736 if ((gr = getgrnam(sp)) == NULL)
737 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
738 li->li_number = gr->gr_gid;
741 if (strcmp(sp, "-") == 0) {
744 } else if (strcmp(sp, "co") == 0) {
750 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
751 if (stat(buf, &st) != -1)
754 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
755 if (stat(buf, &st) != -1)
759 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
760 err(STATUS_ERROR, "Cannot access `%s'", sp);
762 foundtty: if ((st.st_mode & S_IFCHR) == 0)
763 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
765 li->li_number = st.st_rdev;
770 if (strcmp(sp, "none") == 0)
772 else if (strcmp(sp, "any") == 0)
774 else if ((jid = jail_getid(sp)) != -1)
776 else if (*ep != '\0')
777 errx(STATUS_BADUSAGE,
778 "Invalid jail ID or name `%s'", sp);
783 li->li_name = strdup(sp);
784 if (li->li_name == NULL)
785 err(STATUS_ERROR, "Cannot allocate memory");
797 takepid(const char *pidfile, int pidfilelock)
799 char *endp, line[BUFSIZ];
803 fh = fopen(pidfile, "r");
805 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
809 * If we can lock pidfile, this means that daemon is not
810 * running, so would be better not to kill some random process.
812 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
814 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
816 if (errno != EWOULDBLOCK) {
818 "Error while locking file '%s'", pidfile);
823 if (fgets(line, sizeof(line), fh) == NULL) {
826 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
829 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
833 rval = strtol(line, &endp, 10);
834 if (*endp != '\0' && !isspace((unsigned char)*endp))
835 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
836 else if (rval < MIN_PID || rval > MAX_PID)
837 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);