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 #include <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/sysctl.h>
40 #include <sys/queue.h>
65 #define STATUS_MATCH 0
66 #define STATUS_NOMATCH 1
67 #define STATUS_BADUSAGE 2
68 #define STATUS_ERROR 3
73 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
74 #define PSKIP(kp) ((kp)->ki_pid == mypid || \
75 (!kthreads && ((kp)->ki_flag & P_KPROC) != 0))
89 SLIST_ENTRY(list) li_chain;
94 SLIST_HEAD(listhead, list);
96 static struct kinfo_proc *plist;
97 static char *selected;
98 static const char *delim = "\n";
101 static int signum = SIGTERM;
104 static int interactive;
107 static int matchargs;
108 static int fullmatch;
110 static int cflags = REG_EXTENDED;
115 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
116 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
117 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
118 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
119 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
120 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
121 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
122 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
123 static struct listhead classlist = SLIST_HEAD_INITIALIZER(classlist);
125 static void usage(void) __attribute__((__noreturn__));
126 static int killact(const struct kinfo_proc *);
127 static int grepact(const struct kinfo_proc *);
128 static void makelist(struct listhead *, enum listtype, char *);
129 static int takepid(const char *, int);
132 main(int argc, char **argv)
134 char *buf, *mstr, **pargv, *p, *q, *pidfile;
135 const char *execf, *coref;
137 int ancestors, debug_opt, did_action;
138 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
140 int (*action)(const struct kinfo_proc *);
141 struct kinfo_proc *kp;
143 struct timeval best_tval;
148 setlocale(LC_ALL, "");
150 if (strcmp(getprogname(), "pgrep") == 0) {
157 if (argc > 1 && p[0] == '-') {
159 i = (int)strtol(p, &q, 10);
165 if (strncasecmp(p, "SIG", 3) == 0)
167 for (i = 1; i < NSIG; i++)
168 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 * If we're not matching args, we only need a buffer large enough to
316 * hold some relatively short error strings. Otherwise, we have to
317 * assume we'll need up to ARG_MAX bytes for arguments.
319 bufsz = _POSIX2_LINE_MAX;
323 arg_max = sysconf(_SC_ARG_MAX);
328 * The absolute worst case scenario is ARG_MAX single-byte
329 * arguments which we'll then separate with spaces and NUL
332 bufsz = (arg_max * 2) + 1;
337 err(STATUS_ERROR, "malloc");
340 * Retrieve the list of running processes from the kernel.
342 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
344 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
347 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
348 * just want processes and not individual kernel threads.
350 if (pidfromfile >= 0)
351 plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
353 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
355 errx(STATUS_ERROR, "Cannot get process list (%s)",
360 * Allocate memory which will be used to keep track of the
363 if ((selected = malloc(nproc)) == NULL) {
364 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
367 memset(selected, 0, nproc);
370 * Refine the selection.
372 for (; *argv != NULL; argv++) {
373 if ((rv = regcomp(®, *argv, cflags)) != 0) {
374 regerror(rv, ®, buf, bufsz);
375 errx(STATUS_BADUSAGE,
376 "Cannot compile regular expression `%s' (%s)",
380 for (i = 0, kp = plist; i < nproc; i++, kp++) {
383 fprintf(stderr, "* Skipped %5d %3d %s\n",
384 kp->ki_pid, kp->ki_uid, kp->ki_comm);
389 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
391 while (jsz < bufsz && *pargv != NULL) {
392 jsz += snprintf(buf + jsz,
394 pargv[1] != NULL ? "%s " : "%s",
402 rv = regexec(®, mstr, 1, ®match, 0);
405 if (regmatch.rm_so == 0 &&
411 } else if (rv != REG_NOMATCH) {
412 regerror(rv, ®, buf, bufsz);
414 "Regular expression evaluation error (%s)",
418 const char *rv_res = "NoMatch";
421 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
422 kp->ki_pid, kp->ki_uid, mstr);
429 for (i = 0, kp = plist; i < nproc; i++, kp++) {
433 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
438 SLIST_FOREACH(li, &ruidlist, li_chain)
439 if (kp->ki_ruid == (uid_t)li->li_number)
441 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
446 SLIST_FOREACH(li, &rgidlist, li_chain)
447 if (kp->ki_rgid == (gid_t)li->li_number)
449 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
454 SLIST_FOREACH(li, &euidlist, li_chain)
455 if (kp->ki_uid == (uid_t)li->li_number)
457 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
462 SLIST_FOREACH(li, &ppidlist, li_chain)
463 if (kp->ki_ppid == (pid_t)li->li_number)
465 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
470 SLIST_FOREACH(li, &pgrplist, li_chain)
471 if (kp->ki_pgid == (pid_t)li->li_number)
473 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
478 SLIST_FOREACH(li, &tdevlist, li_chain) {
479 if (li->li_number == -1 &&
480 (kp->ki_flag & P_CONTROLT) == 0)
482 if (kp->ki_tdev == (dev_t)li->li_number)
485 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
490 SLIST_FOREACH(li, &sidlist, li_chain)
491 if (kp->ki_sid == (pid_t)li->li_number)
493 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
498 SLIST_FOREACH(li, &jidlist, li_chain) {
499 /* A particular jail ID, including 0 (not in jail) */
500 if (kp->ki_jid == (int)li->li_number)
503 if (kp->ki_jid > 0 && li->li_number == -1)
506 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
511 SLIST_FOREACH(li, &classlist, li_chain) {
513 * We skip P_SYSTEM processes to match ps(1) output.
515 if ((kp->ki_flag & P_SYSTEM) == 0 &&
516 strcmp(kp->ki_loginclass, li->li_name) == 0)
519 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
531 for (i = 0, kp = plist; i < nproc; i++, kp++) {
534 if (kp->ki_pid == pid) {
544 break; /* Maybe we're in a jail ? */
549 if (newest || oldest) {
550 best_tval.tv_sec = 0;
551 best_tval.tv_usec = 0;
554 for (i = 0, kp = plist; i < nproc; i++, kp++) {
558 /* The first entry of the list which matched. */
560 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
561 /* This entry is newer than previous "best". */
562 if (oldest) /* but we want the oldest */
565 /* This entry is older than previous "best". */
566 if (newest) /* but we want the newest */
569 /* This entry is better than previous "best" entry. */
570 best_tval.tv_sec = kp->ki_start.tv_sec;
571 best_tval.tv_usec = kp->ki_start.tv_usec;
575 memset(selected, 0, nproc);
577 selected[bestidx] = 1;
581 * Take the appropriate action for each matched process, if any.
584 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
588 if (longfmt && !pgrep) {
590 printf("kill -%d %d\n", signum, kp->ki_pid);
598 if (rv && pgrep && !quiet)
600 if (!did_action && !pgrep && longfmt)
602 "No matching processes belonging to you were found\n");
605 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
614 ustr = "[-LSfilnoqvx] [-d delim]";
616 ustr = "[-signal] [-ILfilnovx]";
619 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
620 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
621 " [-s sid] [-t tty] [-u euid] pattern ...\n",
622 getprogname(), ustr);
624 exit(STATUS_BADUSAGE);
628 show_process(const struct kinfo_proc *kp)
636 if ((longfmt || !pgrep) && matchargs &&
637 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
638 printf("%d ", (int)kp->ki_pid);
639 for (; *argv != NULL; argv++) {
644 } else if (longfmt || !pgrep)
645 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
647 printf("%d", (int)kp->ki_pid);
651 killact(const struct kinfo_proc *kp)
657 * Be careful, ask before killing.
663 first = ch = getchar();
664 while (ch != '\n' && ch != EOF)
666 if (first != 'y' && first != 'Y')
669 if (kill(kp->ki_pid, signum) == -1) {
671 * Check for ESRCH, which indicates that the process
672 * disappeared between us matching it and us
673 * signalling it; don't issue a warning about it.
676 warn("signalling pid %d", (int)kp->ki_pid);
678 * Return 0 to indicate that the process should not be
679 * considered a match, since we didn't actually get to
688 grepact(const struct kinfo_proc *kp)
690 static bool first = true;
692 if (!quiet && !first)
700 makelist(struct listhead *head, enum listtype type, char *src)
707 char *sp, *ep, buf[MAXPATHLEN];
712 while ((sp = strsep(&src, ",")) != NULL) {
716 if ((li = malloc(sizeof(*li))) == NULL) {
717 err(STATUS_ERROR, "Cannot allocate %zu bytes",
721 SLIST_INSERT_HEAD(head, li, li_chain);
724 if (type != LT_CLASS)
725 li->li_number = (uid_t)strtol(sp, &ep, 0);
727 if (type != LT_CLASS && *ep == '\0') {
730 if (li->li_number == 0)
731 li->li_number = getpgrp();
734 if (li->li_number == 0)
735 li->li_number = getsid(mypid);
738 if (li->li_number < 0)
739 errx(STATUS_BADUSAGE,
740 "Negative jail ID `%s'", sp);
741 /* For compatibility with old -j */
742 if (li->li_number == 0)
743 li->li_number = -1; /* any jail */
746 if (li->li_number < 0)
747 errx(STATUS_BADUSAGE,
748 "Negative /dev/pts tty `%s'", sp);
749 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
751 if (stat(buf, &st) != -1)
754 errx(STATUS_BADUSAGE, "No such tty: `"
755 _PATH_DEV "pts/%s'", sp);
756 err(STATUS_ERROR, "Cannot access `"
757 _PATH_DEV "pts/%s'", sp);
767 if ((pw = getpwnam(sp)) == NULL)
768 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
769 li->li_number = pw->pw_uid;
772 if ((gr = getgrnam(sp)) == NULL)
773 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
774 li->li_number = gr->gr_gid;
777 if (strcmp(sp, "-") == 0) {
780 } else if (strcmp(sp, "co") == 0) {
786 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
787 if (stat(buf, &st) != -1)
790 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
791 if (stat(buf, &st) != -1)
795 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
796 err(STATUS_ERROR, "Cannot access `%s'", sp);
798 foundtty: if ((st.st_mode & S_IFCHR) == 0)
799 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
801 li->li_number = st.st_rdev;
806 if (strcmp(sp, "none") == 0)
808 else if (strcmp(sp, "any") == 0)
810 else if ((jid = jail_getid(sp)) != -1)
812 else if (*ep != '\0')
813 errx(STATUS_BADUSAGE,
814 "Invalid jail ID or name `%s'", sp);
819 li->li_name = strdup(sp);
820 if (li->li_name == NULL)
821 err(STATUS_ERROR, "Cannot allocate memory");
833 takepid(const char *pidfile, int pidfilelock)
835 char *endp, line[BUFSIZ];
839 fh = fopen(pidfile, "r");
841 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
845 * If we can lock pidfile, this means that daemon is not
846 * running, so would be better not to kill some random process.
848 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
850 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
852 if (errno != EWOULDBLOCK) {
854 "Error while locking file '%s'", pidfile);
859 if (fgets(line, sizeof(line), fh) == NULL) {
862 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
865 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
869 rval = strtol(line, &endp, 10);
870 if (*endp != '\0' && !isspace((unsigned char)*endp))
871 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
872 else if (rval < MIN_PID || rval > MAX_PID)
873 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);