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.
32 * $FreeBSD: head/bin/pkill/pkill.c 256050 2013-10-04 16:08:44Z trasz $
36 #include <sys/types.h>
37 #include <sys/param.h>
38 #include <sys/sysctl.h>
39 #include <sys/queue.h>
41 #include <sys/fcntl.h>
61 #define STATUS_MATCH 0
62 #define STATUS_NOMATCH 1
63 #define STATUS_BADUSAGE 2
64 #define STATUS_ERROR 3
69 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
70 #define PSKIP(kp) ((kp)->kp_pid == mypid || \
71 (!kthreads && ((kp)->kp_flags & P_KTHREADP) != 0))
85 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);
119 static struct listhead classlist = SLIST_HEAD_INITIALIZER(classlist);
121 static void usage(void) __attribute__((__noreturn__));
122 static int killact(const struct kinfo_proc *);
123 static int grepact(const struct kinfo_proc *);
124 static void makelist(struct listhead *, enum listtype, char *);
125 static int takepid(const char *, int);
128 main(int argc, char **argv)
130 char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
131 const char *execf, *coref;
132 int ancestors, debug_opt, did_action;
133 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
135 int (*action)(const struct kinfo_proc *);
136 struct kinfo_proc *kp;
138 struct timeval best_tval;
143 setlocale(LC_ALL, "");
145 if (strcmp(getprogname(), "pgrep") == 0) {
152 if (argc > 1 && p[0] == '-') {
154 i = (int)strtol(p, &q, 10);
160 if (strncasecmp(p, "SIG", 3) == 0)
162 for (i = 1; i < NSIG; i++)
163 if (strcasecmp(sys_signame[i], p) == 0)
181 coref = _PATH_DEVNULL;
183 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1)
193 makelist(&rgidlist, LT_GROUP, optarg);
211 makelist(&ppidlist, LT_GENERIC, optarg);
220 makelist(&ruidlist, LT_USER, optarg);
227 makelist(&classlist, LT_CLASS, optarg);
239 makelist(&pgrplist, LT_PGRP, optarg);
246 makelist(&jidlist, LT_JID, optarg);
266 makelist(&sidlist, LT_SID, optarg);
270 makelist(&tdevlist, LT_TTY, optarg);
274 makelist(&euidlist, LT_USER, optarg);
294 if (newest && oldest)
295 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
297 pidfromfile = takepid(pidfile, pidfilelock);
301 "Option -L doesn't make sense without -F");
309 * Retrieve the list of running processes from the kernel.
311 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
313 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
315 if (pidfromfile >= 0)
316 plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
318 plist = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
320 errx(STATUS_ERROR, "Cannot get process list (%s)",
325 * Allocate memory which will be used to keep track of the
328 if ((selected = malloc(nproc)) == NULL) {
329 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
332 memset(selected, 0, nproc);
335 * Refine the selection.
337 for (; *argv != NULL; argv++) {
338 if ((rv = regcomp(®, *argv, cflags)) != 0) {
339 regerror(rv, ®, buf, sizeof(buf));
340 errx(STATUS_BADUSAGE,
341 "Cannot compile regular expression `%s' (%s)",
345 for (i = 0, kp = plist; i < nproc; i++, kp++) {
348 fprintf(stderr, "* Skipped %5d %3d %s\n",
349 kp->kp_pid, kp->kp_uid, kp->kp_comm);
354 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
356 while (jsz < sizeof(buf) && *pargv != NULL) {
357 jsz += snprintf(buf + jsz,
359 pargv[1] != NULL ? "%s " : "%s",
367 rv = regexec(®, mstr, 1, ®match, 0);
370 if (regmatch.rm_so == 0 &&
376 } else if (rv != REG_NOMATCH) {
377 regerror(rv, ®, buf, sizeof(buf));
379 "Regular expression evaluation error (%s)",
383 const char *rv_res = "NoMatch";
386 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
387 kp->kp_pid, kp->kp_uid, mstr);
394 for (i = 0, kp = plist; i < nproc; i++, kp++) {
398 if (pidfromfile >= 0 && kp->kp_pid != pidfromfile) {
403 SLIST_FOREACH(li, &ruidlist, li_chain)
404 if (kp->kp_ruid == (uid_t)li->li_number)
406 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
411 SLIST_FOREACH(li, &rgidlist, li_chain)
412 if (kp->kp_rgid == (gid_t)li->li_number)
414 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
419 SLIST_FOREACH(li, &euidlist, li_chain)
420 if (kp->kp_uid == (uid_t)li->li_number)
422 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
427 SLIST_FOREACH(li, &ppidlist, li_chain)
428 if (kp->kp_ppid == (pid_t)li->li_number)
430 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
435 SLIST_FOREACH(li, &pgrplist, li_chain)
436 if (kp->kp_pgid == (pid_t)li->li_number)
438 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
443 SLIST_FOREACH(li, &tdevlist, li_chain) {
444 if (li->li_number == -1 &&
445 (kp->kp_flags & P_CONTROLT) == 0)
447 if (kp->kp_tdev == (dev_t)li->li_number)
450 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
455 SLIST_FOREACH(li, &sidlist, li_chain)
456 if (kp->kp_sid == (pid_t)li->li_number)
458 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
463 SLIST_FOREACH(li, &jidlist, li_chain) {
464 /* A particular jail ID, including 0 (not in jail) */
465 if (kp->kp_jailid == (int)li->li_number)
468 if (kp->kp_jailid > 0 && li->li_number == -1)
471 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
476 SLIST_FOREACH(li, &classlist, li_chain) {
478 * We skip P_SYSTEM processes to match ps(1) output.
480 if ((kp->kp_flags & P_SYSTEM) == 0)
483 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
495 for (i = 0, kp = plist; i < nproc; i++, kp++) {
498 if (kp->kp_pid == pid) {
508 break; /* Maybe we're in a jail ? */
513 if (newest || oldest) {
514 best_tval.tv_sec = 0;
515 best_tval.tv_usec = 0;
518 for (i = 0, kp = plist; i < nproc; i++, kp++) {
522 /* The first entry of the list which matched. */
524 } else if (timercmp(&kp->kp_start, &best_tval, >)) {
525 /* This entry is newer than previous "best". */
526 if (oldest) /* but we want the oldest */
529 /* This entry is older than previous "best". */
530 if (newest) /* but we want the newest */
533 /* This entry is better than previous "best" entry. */
534 best_tval.tv_sec = kp->kp_start.tv_sec;
535 best_tval.tv_usec = kp->kp_start.tv_usec;
539 memset(selected, 0, nproc);
541 selected[bestidx] = 1;
545 * Take the appropriate action for each matched process, if any.
548 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
552 if (longfmt && !pgrep) {
554 printf("kill -%d %d\n", signum, kp->kp_pid);
562 if (!did_action && !pgrep && longfmt)
564 "No matching processes belonging to you were found\n");
566 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
575 ustr = "[-LSfilnoqvx] [-d delim]";
577 ustr = "[-signal] [-ILfilnovx]";
580 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
581 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jid]\n"
582 " [-s sid] [-t tty] [-u euid] pattern ...\n",
583 getprogname(), ustr);
585 exit(STATUS_BADUSAGE);
589 show_process(const struct kinfo_proc *kp)
597 if ((longfmt || !pgrep) && matchargs &&
598 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
599 printf("%d ", (int)kp->kp_pid);
600 for (; *argv != NULL; argv++) {
605 } else if (longfmt || !pgrep)
606 printf("%d %s", (int)kp->kp_pid, kp->kp_comm);
608 printf("%d", (int)kp->kp_pid);
612 killact(const struct kinfo_proc *kp)
618 * Be careful, ask before killing.
624 first = ch = getchar();
625 while (ch != '\n' && ch != EOF)
627 if (first != 'y' && first != 'Y')
630 if (kill(kp->kp_pid, signum) == -1) {
632 * Check for ESRCH, which indicates that the process
633 * disappeared between us matching it and us
634 * signalling it; don't issue a warning about it.
637 warn("signalling pid %d", (int)kp->kp_pid);
639 * Return 0 to indicate that the process should not be
640 * considered a match, since we didn't actually get to
649 grepact(const struct kinfo_proc *kp)
659 makelist(struct listhead *head, enum listtype type, char *src)
666 char *sp, *ep, buf[MAXPATHLEN];
671 while ((sp = strsep(&src, ",")) != NULL) {
675 if ((li = malloc(sizeof(*li))) == NULL) {
676 err(STATUS_ERROR, "Cannot allocate %zu bytes",
680 SLIST_INSERT_HEAD(head, li, li_chain);
683 if (type != LT_CLASS)
684 li->li_number = (uid_t)strtol(sp, &ep, 0);
686 if (type != LT_CLASS && *ep == '\0') {
689 if (li->li_number == 0)
690 li->li_number = getpgrp();
693 if (li->li_number == 0)
694 li->li_number = getsid(mypid);
697 if (li->li_number < 0)
698 errx(STATUS_BADUSAGE,
699 "Negative jail ID `%s'", sp);
700 /* For compatibility with old -j */
701 if (li->li_number == 0)
702 li->li_number = -1; /* any jail */
705 if (li->li_number < 0)
706 errx(STATUS_BADUSAGE,
707 "Negative /dev/pts tty `%s'", sp);
708 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
710 if (stat(buf, &st) != -1)
713 errx(STATUS_BADUSAGE, "No such tty: `"
714 _PATH_DEV "pts/%s'", sp);
715 err(STATUS_ERROR, "Cannot access `"
716 _PATH_DEV "pts/%s'", sp);
726 if ((pw = getpwnam(sp)) == NULL)
727 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
728 li->li_number = pw->pw_uid;
731 if ((gr = getgrnam(sp)) == NULL)
732 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
733 li->li_number = gr->gr_gid;
736 if (strcmp(sp, "-") == 0) {
739 } else if (strcmp(sp, "co") == 0) {
745 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
746 if (stat(buf, &st) != -1)
749 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
750 if (stat(buf, &st) != -1)
754 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
755 err(STATUS_ERROR, "Cannot access `%s'", sp);
757 foundtty: if ((st.st_mode & S_IFCHR) == 0)
758 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
760 li->li_number = st.st_rdev;
763 if (strcmp(sp, "none") == 0)
765 else if (strcmp(sp, "any") == 0)
767 else if (*ep != '\0')
768 errx(STATUS_BADUSAGE,
769 "Invalid jail ID `%s'", sp);
773 li->li_name = strdup(sp);
774 if (li->li_name == NULL)
775 err(STATUS_ERROR, "Cannot allocate memory");
787 takepid(const char *pidfile, int pidfilelock)
789 char *endp, line[BUFSIZ];
793 fh = fopen(pidfile, "r");
795 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
799 * If we can lock pidfile, this means that daemon is not
800 * running, so would be better not to kill some random process.
802 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
804 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
806 if (errno != EWOULDBLOCK) {
808 "Error while locking file '%s'", pidfile);
813 if (fgets(line, sizeof(line), fh) == NULL) {
816 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
819 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
823 rval = strtol(line, &endp, 10);
824 if (*endp != '\0' && !isspace((unsigned char)*endp))
825 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
826 else if (rval < MIN_PID || rval > MAX_PID)
827 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);