1 /* $NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause-NetBSD
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[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
137 const char *execf, *coref;
138 int ancestors, debug_opt, did_action;
139 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
141 int (*action)(const struct kinfo_proc *);
142 struct kinfo_proc *kp;
144 struct timeval best_tval;
149 setlocale(LC_ALL, "");
151 if (strcmp(getprogname(), "pgrep") == 0) {
158 if (argc > 1 && p[0] == '-') {
160 i = (int)strtol(p, &q, 10);
166 if (strncasecmp(p, "SIG", 3) == 0)
168 for (i = 1; i < NSIG; i++)
169 if (strcasecmp(sys_signame[i], p) == 0)
187 coref = _PATH_DEVNULL;
189 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1)
199 makelist(&rgidlist, LT_GROUP, optarg);
217 makelist(&ppidlist, LT_GENERIC, optarg);
226 makelist(&ruidlist, LT_USER, optarg);
233 makelist(&classlist, LT_CLASS, optarg);
245 makelist(&pgrplist, LT_PGRP, optarg);
252 makelist(&jidlist, LT_JAIL, optarg);
272 makelist(&sidlist, LT_SID, optarg);
276 makelist(&tdevlist, LT_TTY, optarg);
280 makelist(&euidlist, LT_USER, optarg);
300 if (newest && oldest)
301 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
303 pidfromfile = takepid(pidfile, pidfilelock);
307 "Option -L doesn't make sense without -F");
315 * Retrieve the list of running processes from the kernel.
317 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
319 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
322 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
323 * just want processes and not individual kernel threads.
325 if (pidfromfile >= 0)
326 plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
328 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
330 errx(STATUS_ERROR, "Cannot get process list (%s)",
335 * Allocate memory which will be used to keep track of the
338 if ((selected = malloc(nproc)) == NULL) {
339 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
342 memset(selected, 0, nproc);
345 * Refine the selection.
347 for (; *argv != NULL; argv++) {
348 if ((rv = regcomp(®, *argv, cflags)) != 0) {
349 regerror(rv, ®, buf, sizeof(buf));
350 errx(STATUS_BADUSAGE,
351 "Cannot compile regular expression `%s' (%s)",
355 for (i = 0, kp = plist; i < nproc; i++, kp++) {
358 fprintf(stderr, "* Skipped %5d %3d %s\n",
359 kp->ki_pid, kp->ki_uid, kp->ki_comm);
364 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
366 while (jsz < sizeof(buf) && *pargv != NULL) {
367 jsz += snprintf(buf + jsz,
369 pargv[1] != NULL ? "%s " : "%s",
377 rv = regexec(®, mstr, 1, ®match, 0);
380 if (regmatch.rm_so == 0 &&
386 } else if (rv != REG_NOMATCH) {
387 regerror(rv, ®, buf, sizeof(buf));
389 "Regular expression evaluation error (%s)",
393 const char *rv_res = "NoMatch";
396 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
397 kp->ki_pid, kp->ki_uid, mstr);
404 for (i = 0, kp = plist; i < nproc; i++, kp++) {
408 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
413 SLIST_FOREACH(li, &ruidlist, li_chain)
414 if (kp->ki_ruid == (uid_t)li->li_number)
416 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
421 SLIST_FOREACH(li, &rgidlist, li_chain)
422 if (kp->ki_rgid == (gid_t)li->li_number)
424 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
429 SLIST_FOREACH(li, &euidlist, li_chain)
430 if (kp->ki_uid == (uid_t)li->li_number)
432 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
437 SLIST_FOREACH(li, &ppidlist, li_chain)
438 if (kp->ki_ppid == (pid_t)li->li_number)
440 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
445 SLIST_FOREACH(li, &pgrplist, li_chain)
446 if (kp->ki_pgid == (pid_t)li->li_number)
448 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
453 SLIST_FOREACH(li, &tdevlist, li_chain) {
454 if (li->li_number == -1 &&
455 (kp->ki_flag & P_CONTROLT) == 0)
457 if (kp->ki_tdev == (dev_t)li->li_number)
460 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
465 SLIST_FOREACH(li, &sidlist, li_chain)
466 if (kp->ki_sid == (pid_t)li->li_number)
468 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
473 SLIST_FOREACH(li, &jidlist, li_chain) {
474 /* A particular jail ID, including 0 (not in jail) */
475 if (kp->ki_jid == (int)li->li_number)
478 if (kp->ki_jid > 0 && li->li_number == -1)
481 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
486 SLIST_FOREACH(li, &classlist, li_chain) {
488 * We skip P_SYSTEM processes to match ps(1) output.
490 if ((kp->ki_flag & P_SYSTEM) == 0 &&
491 strcmp(kp->ki_loginclass, li->li_name) == 0)
494 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
506 for (i = 0, kp = plist; i < nproc; i++, kp++) {
509 if (kp->ki_pid == pid) {
519 break; /* Maybe we're in a jail ? */
524 if (newest || oldest) {
525 best_tval.tv_sec = 0;
526 best_tval.tv_usec = 0;
529 for (i = 0, kp = plist; i < nproc; i++, kp++) {
533 /* The first entry of the list which matched. */
535 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
536 /* This entry is newer than previous "best". */
537 if (oldest) /* but we want the oldest */
540 /* This entry is older than previous "best". */
541 if (newest) /* but we want the newest */
544 /* This entry is better than previous "best" entry. */
545 best_tval.tv_sec = kp->ki_start.tv_sec;
546 best_tval.tv_usec = kp->ki_start.tv_usec;
550 memset(selected, 0, nproc);
552 selected[bestidx] = 1;
556 * Take the appropriate action for each matched process, if any.
559 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
563 if (longfmt && !pgrep) {
565 printf("kill -%d %d\n", signum, kp->ki_pid);
573 if (rv && pgrep && !quiet)
575 if (!did_action && !pgrep && longfmt)
577 "No matching processes belonging to you were found\n");
579 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
588 ustr = "[-LSfilnoqvx] [-d delim]";
590 ustr = "[-signal] [-ILfilnovx]";
593 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
594 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
595 " [-s sid] [-t tty] [-u euid] pattern ...\n",
596 getprogname(), ustr);
598 exit(STATUS_BADUSAGE);
602 show_process(const struct kinfo_proc *kp)
610 if ((longfmt || !pgrep) && matchargs &&
611 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
612 printf("%d ", (int)kp->ki_pid);
613 for (; *argv != NULL; argv++) {
618 } else if (longfmt || !pgrep)
619 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
621 printf("%d", (int)kp->ki_pid);
625 killact(const struct kinfo_proc *kp)
631 * Be careful, ask before killing.
637 first = ch = getchar();
638 while (ch != '\n' && ch != EOF)
640 if (first != 'y' && first != 'Y')
643 if (kill(kp->ki_pid, signum) == -1) {
645 * Check for ESRCH, which indicates that the process
646 * disappeared between us matching it and us
647 * signalling it; don't issue a warning about it.
650 warn("signalling pid %d", (int)kp->ki_pid);
652 * Return 0 to indicate that the process should not be
653 * considered a match, since we didn't actually get to
662 grepact(const struct kinfo_proc *kp)
664 static bool first = true;
666 if (!quiet && !first)
674 makelist(struct listhead *head, enum listtype type, char *src)
681 char *sp, *ep, buf[MAXPATHLEN];
686 while ((sp = strsep(&src, ",")) != NULL) {
690 if ((li = malloc(sizeof(*li))) == NULL) {
691 err(STATUS_ERROR, "Cannot allocate %zu bytes",
695 SLIST_INSERT_HEAD(head, li, li_chain);
698 if (type != LT_CLASS)
699 li->li_number = (uid_t)strtol(sp, &ep, 0);
701 if (type != LT_CLASS && *ep == '\0') {
704 if (li->li_number == 0)
705 li->li_number = getpgrp();
708 if (li->li_number == 0)
709 li->li_number = getsid(mypid);
712 if (li->li_number < 0)
713 errx(STATUS_BADUSAGE,
714 "Negative jail ID `%s'", sp);
715 /* For compatibility with old -j */
716 if (li->li_number == 0)
717 li->li_number = -1; /* any jail */
720 if (li->li_number < 0)
721 errx(STATUS_BADUSAGE,
722 "Negative /dev/pts tty `%s'", sp);
723 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
725 if (stat(buf, &st) != -1)
728 errx(STATUS_BADUSAGE, "No such tty: `"
729 _PATH_DEV "pts/%s'", sp);
730 err(STATUS_ERROR, "Cannot access `"
731 _PATH_DEV "pts/%s'", sp);
741 if ((pw = getpwnam(sp)) == NULL)
742 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
743 li->li_number = pw->pw_uid;
746 if ((gr = getgrnam(sp)) == NULL)
747 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
748 li->li_number = gr->gr_gid;
751 if (strcmp(sp, "-") == 0) {
754 } else if (strcmp(sp, "co") == 0) {
760 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
761 if (stat(buf, &st) != -1)
764 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
765 if (stat(buf, &st) != -1)
769 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
770 err(STATUS_ERROR, "Cannot access `%s'", sp);
772 foundtty: if ((st.st_mode & S_IFCHR) == 0)
773 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
775 li->li_number = st.st_rdev;
780 if (strcmp(sp, "none") == 0)
782 else if (strcmp(sp, "any") == 0)
784 else if ((jid = jail_getid(sp)) != -1)
786 else if (*ep != '\0')
787 errx(STATUS_BADUSAGE,
788 "Invalid jail ID or name `%s'", sp);
793 li->li_name = strdup(sp);
794 if (li->li_name == NULL)
795 err(STATUS_ERROR, "Cannot allocate memory");
807 takepid(const char *pidfile, int pidfilelock)
809 char *endp, line[BUFSIZ];
813 fh = fopen(pidfile, "r");
815 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
819 * If we can lock pidfile, this means that daemon is not
820 * running, so would be better not to kill some random process.
822 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
824 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
826 if (errno != EWOULDBLOCK) {
828 "Error while locking file '%s'", pidfile);
833 if (fgets(line, sizeof(line), fh) == NULL) {
836 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
839 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
843 rval = strtol(line, &endp, 10);
844 if (*endp != '\0' && !isspace((unsigned char)*endp))
845 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
846 else if (rval < MIN_PID || rval > MAX_PID)
847 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);