1 /* $NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 2002 The NetBSD Foundation, Inc.
7 * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
10 * This code is derived from software contributed to The NetBSD Foundation
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/sysctl.h>
42 #include <sys/queue.h>
67 #define STATUS_MATCH 0
68 #define STATUS_NOMATCH 1
69 #define STATUS_BADUSAGE 2
70 #define STATUS_ERROR 3
75 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
76 #define PSKIP(kp) ((kp)->ki_pid == mypid || \
77 (!kthreads && ((kp)->ki_flag & P_KPROC) != 0))
91 SLIST_ENTRY(list) li_chain;
96 SLIST_HEAD(listhead, list);
98 static struct kinfo_proc *plist;
99 static char *selected;
100 static const char *delim = "\n";
103 static int signum = SIGTERM;
106 static int interactive;
109 static int matchargs;
110 static int fullmatch;
112 static int cflags = REG_EXTENDED;
117 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
118 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
119 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
120 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
121 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
122 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
123 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
124 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
125 static struct listhead classlist = SLIST_HEAD_INITIALIZER(classlist);
127 static void usage(void) __attribute__((__noreturn__));
128 static int killact(const struct kinfo_proc *);
129 static int grepact(const struct kinfo_proc *);
130 static void makelist(struct listhead *, enum listtype, char *);
131 static int takepid(const char *, int);
134 main(int argc, char **argv)
136 char *buf, *mstr, **pargv, *p, *q, *pidfile;
137 const char *execf, *coref;
139 int ancestors, debug_opt, did_action;
140 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
142 int (*action)(const struct kinfo_proc *);
143 struct kinfo_proc *kp;
145 struct timeval best_tval;
150 setlocale(LC_ALL, "");
152 if (strcmp(getprogname(), "pgrep") == 0) {
159 if (argc > 1 && p[0] == '-') {
161 i = (int)strtol(p, &q, 10);
167 if (strncasecmp(p, "SIG", 3) == 0)
169 for (i = 1; i < NSIG; i++)
170 if (strcasecmp(sys_signame[i], p) == 0)
189 coref = _PATH_DEVNULL;
191 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1)
201 makelist(&rgidlist, LT_GROUP, optarg);
219 makelist(&ppidlist, LT_GENERIC, optarg);
228 makelist(&ruidlist, LT_USER, optarg);
235 makelist(&classlist, LT_CLASS, optarg);
247 makelist(&pgrplist, LT_PGRP, optarg);
254 makelist(&jidlist, LT_JAIL, optarg);
274 makelist(&sidlist, LT_SID, optarg);
278 makelist(&tdevlist, LT_TTY, optarg);
282 makelist(&euidlist, LT_USER, optarg);
302 if (newest && oldest)
303 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
305 pidfromfile = takepid(pidfile, pidfilelock);
309 "Option -L doesn't make sense without -F");
317 * If we're not matching args, we only need a buffer large enough to
318 * hold some relatively short error strings. Otherwise, we have to
319 * assume we'll need up to ARG_MAX bytes for arguments.
321 bufsz = _POSIX2_LINE_MAX;
325 arg_max = sysconf(_SC_ARG_MAX);
330 * The absolute worst case scenario is ARG_MAX single-byte
331 * arguments which we'll then separate with spaces and NUL
334 bufsz = (arg_max * 2) + 1;
339 err(STATUS_ERROR, "malloc");
342 * Retrieve the list of running processes from the kernel.
344 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
346 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
349 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
350 * just want processes and not individual kernel threads.
352 if (pidfromfile >= 0)
353 plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
355 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
357 errx(STATUS_ERROR, "Cannot get process list (%s)",
362 * Allocate memory which will be used to keep track of the
365 if ((selected = malloc(nproc)) == NULL) {
366 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
369 memset(selected, 0, nproc);
372 * Refine the selection.
374 for (; *argv != NULL; argv++) {
375 if ((rv = regcomp(®, *argv, cflags)) != 0) {
376 regerror(rv, ®, buf, bufsz);
377 errx(STATUS_BADUSAGE,
378 "Cannot compile regular expression `%s' (%s)",
382 for (i = 0, kp = plist; i < nproc; i++, kp++) {
385 fprintf(stderr, "* Skipped %5d %3d %s\n",
386 kp->ki_pid, kp->ki_uid, kp->ki_comm);
391 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
393 while (jsz < bufsz && *pargv != NULL) {
394 jsz += snprintf(buf + jsz,
396 pargv[1] != NULL ? "%s " : "%s",
404 rv = regexec(®, mstr, 1, ®match, 0);
407 if (regmatch.rm_so == 0 &&
413 } else if (rv != REG_NOMATCH) {
414 regerror(rv, ®, buf, bufsz);
416 "Regular expression evaluation error (%s)",
420 const char *rv_res = "NoMatch";
423 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
424 kp->ki_pid, kp->ki_uid, mstr);
431 for (i = 0, kp = plist; i < nproc; i++, kp++) {
435 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
440 SLIST_FOREACH(li, &ruidlist, li_chain)
441 if (kp->ki_ruid == (uid_t)li->li_number)
443 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
448 SLIST_FOREACH(li, &rgidlist, li_chain)
449 if (kp->ki_rgid == (gid_t)li->li_number)
451 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
456 SLIST_FOREACH(li, &euidlist, li_chain)
457 if (kp->ki_uid == (uid_t)li->li_number)
459 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
464 SLIST_FOREACH(li, &ppidlist, li_chain)
465 if (kp->ki_ppid == (pid_t)li->li_number)
467 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
472 SLIST_FOREACH(li, &pgrplist, li_chain)
473 if (kp->ki_pgid == (pid_t)li->li_number)
475 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
480 SLIST_FOREACH(li, &tdevlist, li_chain) {
481 if (li->li_number == -1 &&
482 (kp->ki_flag & P_CONTROLT) == 0)
484 if (kp->ki_tdev == (dev_t)li->li_number)
487 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
492 SLIST_FOREACH(li, &sidlist, li_chain)
493 if (kp->ki_sid == (pid_t)li->li_number)
495 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
500 SLIST_FOREACH(li, &jidlist, li_chain) {
501 /* A particular jail ID, including 0 (not in jail) */
502 if (kp->ki_jid == (int)li->li_number)
505 if (kp->ki_jid > 0 && li->li_number == -1)
508 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
513 SLIST_FOREACH(li, &classlist, li_chain) {
515 * We skip P_SYSTEM processes to match ps(1) output.
517 if ((kp->ki_flag & P_SYSTEM) == 0 &&
518 strcmp(kp->ki_loginclass, li->li_name) == 0)
521 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
533 for (i = 0, kp = plist; i < nproc; i++, kp++) {
536 if (kp->ki_pid == pid) {
546 break; /* Maybe we're in a jail ? */
551 if (newest || oldest) {
552 best_tval.tv_sec = 0;
553 best_tval.tv_usec = 0;
556 for (i = 0, kp = plist; i < nproc; i++, kp++) {
560 /* The first entry of the list which matched. */
562 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
563 /* This entry is newer than previous "best". */
564 if (oldest) /* but we want the oldest */
567 /* This entry is older than previous "best". */
568 if (newest) /* but we want the newest */
571 /* This entry is better than previous "best" entry. */
572 best_tval.tv_sec = kp->ki_start.tv_sec;
573 best_tval.tv_usec = kp->ki_start.tv_usec;
577 memset(selected, 0, nproc);
579 selected[bestidx] = 1;
583 * Take the appropriate action for each matched process, if any.
586 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
590 if (longfmt && !pgrep) {
592 printf("kill -%d %d\n", signum, kp->ki_pid);
600 if (rv && pgrep && !quiet)
602 if (!did_action && !pgrep && longfmt)
604 "No matching processes belonging to you were found\n");
607 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
616 ustr = "[-LSfilnoqvx] [-d delim]";
618 ustr = "[-signal] [-ILfilnovx]";
621 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
622 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
623 " [-s sid] [-t tty] [-u euid] pattern ...\n",
624 getprogname(), ustr);
626 exit(STATUS_BADUSAGE);
630 show_process(const struct kinfo_proc *kp)
638 if ((longfmt || !pgrep) && matchargs &&
639 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
640 printf("%d ", (int)kp->ki_pid);
641 for (; *argv != NULL; argv++) {
646 } else if (longfmt || !pgrep)
647 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
649 printf("%d", (int)kp->ki_pid);
653 killact(const struct kinfo_proc *kp)
659 * Be careful, ask before killing.
665 first = ch = getchar();
666 while (ch != '\n' && ch != EOF)
668 if (first != 'y' && first != 'Y')
671 if (kill(kp->ki_pid, signum) == -1) {
673 * Check for ESRCH, which indicates that the process
674 * disappeared between us matching it and us
675 * signalling it; don't issue a warning about it.
678 warn("signalling pid %d", (int)kp->ki_pid);
680 * Return 0 to indicate that the process should not be
681 * considered a match, since we didn't actually get to
690 grepact(const struct kinfo_proc *kp)
692 static bool first = true;
694 if (!quiet && !first)
702 makelist(struct listhead *head, enum listtype type, char *src)
709 char *sp, *ep, buf[MAXPATHLEN];
714 while ((sp = strsep(&src, ",")) != NULL) {
718 if ((li = malloc(sizeof(*li))) == NULL) {
719 err(STATUS_ERROR, "Cannot allocate %zu bytes",
723 SLIST_INSERT_HEAD(head, li, li_chain);
726 if (type != LT_CLASS)
727 li->li_number = (uid_t)strtol(sp, &ep, 0);
729 if (type != LT_CLASS && *ep == '\0') {
732 if (li->li_number == 0)
733 li->li_number = getpgrp();
736 if (li->li_number == 0)
737 li->li_number = getsid(mypid);
740 if (li->li_number < 0)
741 errx(STATUS_BADUSAGE,
742 "Negative jail ID `%s'", sp);
743 /* For compatibility with old -j */
744 if (li->li_number == 0)
745 li->li_number = -1; /* any jail */
748 if (li->li_number < 0)
749 errx(STATUS_BADUSAGE,
750 "Negative /dev/pts tty `%s'", sp);
751 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
753 if (stat(buf, &st) != -1)
756 errx(STATUS_BADUSAGE, "No such tty: `"
757 _PATH_DEV "pts/%s'", sp);
758 err(STATUS_ERROR, "Cannot access `"
759 _PATH_DEV "pts/%s'", sp);
769 if ((pw = getpwnam(sp)) == NULL)
770 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
771 li->li_number = pw->pw_uid;
774 if ((gr = getgrnam(sp)) == NULL)
775 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
776 li->li_number = gr->gr_gid;
779 if (strcmp(sp, "-") == 0) {
782 } else if (strcmp(sp, "co") == 0) {
788 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
789 if (stat(buf, &st) != -1)
792 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
793 if (stat(buf, &st) != -1)
797 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
798 err(STATUS_ERROR, "Cannot access `%s'", sp);
800 foundtty: if ((st.st_mode & S_IFCHR) == 0)
801 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
803 li->li_number = st.st_rdev;
808 if (strcmp(sp, "none") == 0)
810 else if (strcmp(sp, "any") == 0)
812 else if ((jid = jail_getid(sp)) != -1)
814 else if (*ep != '\0')
815 errx(STATUS_BADUSAGE,
816 "Invalid jail ID or name `%s'", sp);
821 li->li_name = strdup(sp);
822 if (li->li_name == NULL)
823 err(STATUS_ERROR, "Cannot allocate memory");
835 takepid(const char *pidfile, int pidfilelock)
837 char *endp, line[BUFSIZ];
841 fh = fopen(pidfile, "r");
843 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
847 * If we can lock pidfile, this means that daemon is not
848 * running, so would be better not to kill some random process.
850 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
852 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
854 if (errno != EWOULDBLOCK) {
856 "Error while locking file '%s'", pidfile);
861 if (fgets(line, sizeof(line), fh) == NULL) {
864 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
867 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
871 rval = strtol(line, &endp, 10);
872 if (*endp != '\0' && !isspace((unsigned char)*endp))
873 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
874 else if (rval < MIN_PID || rval > MAX_PID)
875 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);