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>
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[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q, *pidfile;
135 const char *execf, *coref;
136 int ancestors, debug_opt, did_action;
137 int i, ch, bestidx, rv, criteria, pidfromfile, pidfilelock;
139 int (*action)(const struct kinfo_proc *);
140 struct kinfo_proc *kp;
142 struct timeval best_tval;
147 setlocale(LC_ALL, "");
149 if (strcmp(getprogname(), "pgrep") == 0) {
156 if (argc > 1 && p[0] == '-') {
158 i = (int)strtol(p, &q, 10);
164 if (strncasecmp(p, "SIG", 3) == 0)
166 for (i = 1; i < NSIG; i++)
167 if (strcasecmp(sys_signame[i], p) == 0)
185 coref = _PATH_DEVNULL;
187 while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1)
197 makelist(&rgidlist, LT_GROUP, optarg);
215 makelist(&ppidlist, LT_GENERIC, optarg);
224 makelist(&ruidlist, LT_USER, optarg);
231 makelist(&classlist, LT_CLASS, optarg);
243 makelist(&pgrplist, LT_PGRP, optarg);
250 makelist(&jidlist, LT_JAIL, optarg);
270 makelist(&sidlist, LT_SID, optarg);
274 makelist(&tdevlist, LT_TTY, optarg);
278 makelist(&euidlist, LT_USER, optarg);
298 if (newest && oldest)
299 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
301 pidfromfile = takepid(pidfile, pidfilelock);
305 "Option -L doesn't make sense without -F");
313 * Retrieve the list of running processes from the kernel.
315 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
317 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
320 * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
321 * just want processes and not individual kernel threads.
323 if (pidfromfile >= 0)
324 plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
326 plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
328 errx(STATUS_ERROR, "Cannot get process list (%s)",
333 * Allocate memory which will be used to keep track of the
336 if ((selected = malloc(nproc)) == NULL) {
337 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
340 memset(selected, 0, nproc);
343 * Refine the selection.
345 for (; *argv != NULL; argv++) {
346 if ((rv = regcomp(®, *argv, cflags)) != 0) {
347 regerror(rv, ®, buf, sizeof(buf));
348 errx(STATUS_BADUSAGE,
349 "Cannot compile regular expression `%s' (%s)",
353 for (i = 0, kp = plist; i < nproc; i++, kp++) {
356 fprintf(stderr, "* Skipped %5d %3d %s\n",
357 kp->ki_pid, kp->ki_uid, kp->ki_comm);
362 (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
364 while (jsz < sizeof(buf) && *pargv != NULL) {
365 jsz += snprintf(buf + jsz,
367 pargv[1] != NULL ? "%s " : "%s",
375 rv = regexec(®, mstr, 1, ®match, 0);
378 if (regmatch.rm_so == 0 &&
384 } else if (rv != REG_NOMATCH) {
385 regerror(rv, ®, buf, sizeof(buf));
387 "Regular expression evaluation error (%s)",
391 const char *rv_res = "NoMatch";
394 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
395 kp->ki_pid, kp->ki_uid, mstr);
402 for (i = 0, kp = plist; i < nproc; i++, kp++) {
406 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
411 SLIST_FOREACH(li, &ruidlist, li_chain)
412 if (kp->ki_ruid == (uid_t)li->li_number)
414 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
419 SLIST_FOREACH(li, &rgidlist, li_chain)
420 if (kp->ki_rgid == (gid_t)li->li_number)
422 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
427 SLIST_FOREACH(li, &euidlist, li_chain)
428 if (kp->ki_uid == (uid_t)li->li_number)
430 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
435 SLIST_FOREACH(li, &ppidlist, li_chain)
436 if (kp->ki_ppid == (pid_t)li->li_number)
438 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
443 SLIST_FOREACH(li, &pgrplist, li_chain)
444 if (kp->ki_pgid == (pid_t)li->li_number)
446 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
451 SLIST_FOREACH(li, &tdevlist, li_chain) {
452 if (li->li_number == -1 &&
453 (kp->ki_flag & P_CONTROLT) == 0)
455 if (kp->ki_tdev == (dev_t)li->li_number)
458 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
463 SLIST_FOREACH(li, &sidlist, li_chain)
464 if (kp->ki_sid == (pid_t)li->li_number)
466 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
471 SLIST_FOREACH(li, &jidlist, li_chain) {
472 /* A particular jail ID, including 0 (not in jail) */
473 if (kp->ki_jid == (int)li->li_number)
476 if (kp->ki_jid > 0 && li->li_number == -1)
479 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
484 SLIST_FOREACH(li, &classlist, li_chain) {
486 * We skip P_SYSTEM processes to match ps(1) output.
488 if ((kp->ki_flag & P_SYSTEM) == 0 &&
489 strcmp(kp->ki_loginclass, li->li_name) == 0)
492 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
504 for (i = 0, kp = plist; i < nproc; i++, kp++) {
507 if (kp->ki_pid == pid) {
517 break; /* Maybe we're in a jail ? */
522 if (newest || oldest) {
523 best_tval.tv_sec = 0;
524 best_tval.tv_usec = 0;
527 for (i = 0, kp = plist; i < nproc; i++, kp++) {
531 /* The first entry of the list which matched. */
533 } else if (timercmp(&kp->ki_start, &best_tval, >)) {
534 /* This entry is newer than previous "best". */
535 if (oldest) /* but we want the oldest */
538 /* This entry is older than previous "best". */
539 if (newest) /* but we want the newest */
542 /* This entry is better than previous "best" entry. */
543 best_tval.tv_sec = kp->ki_start.tv_sec;
544 best_tval.tv_usec = kp->ki_start.tv_usec;
548 memset(selected, 0, nproc);
550 selected[bestidx] = 1;
554 * Take the appropriate action for each matched process, if any.
557 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
561 if (longfmt && !pgrep) {
563 printf("kill -%d %d\n", signum, kp->ki_pid);
573 if (!did_action && !pgrep && longfmt)
575 "No matching processes belonging to you were found\n");
577 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
586 ustr = "[-LSfilnoqvx] [-d delim]";
588 ustr = "[-signal] [-ILfilnovx]";
591 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
592 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jail]\n"
593 " [-s sid] [-t tty] [-u euid] pattern ...\n",
594 getprogname(), ustr);
596 exit(STATUS_BADUSAGE);
600 show_process(const struct kinfo_proc *kp)
608 if ((longfmt || !pgrep) && matchargs &&
609 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
610 printf("%d ", (int)kp->ki_pid);
611 for (; *argv != NULL; argv++) {
616 } else if (longfmt || !pgrep)
617 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
619 printf("%d", (int)kp->ki_pid);
623 killact(const struct kinfo_proc *kp)
629 * Be careful, ask before killing.
635 first = ch = getchar();
636 while (ch != '\n' && ch != EOF)
638 if (first != 'y' && first != 'Y')
641 if (kill(kp->ki_pid, signum) == -1) {
643 * Check for ESRCH, which indicates that the process
644 * disappeared between us matching it and us
645 * signalling it; don't issue a warning about it.
648 warn("signalling pid %d", (int)kp->ki_pid);
650 * Return 0 to indicate that the process should not be
651 * considered a match, since we didn't actually get to
660 grepact(const struct kinfo_proc *kp)
662 static bool first = true;
664 if (!quiet && !first)
672 makelist(struct listhead *head, enum listtype type, char *src)
679 char *sp, *ep, buf[MAXPATHLEN];
684 while ((sp = strsep(&src, ",")) != NULL) {
688 if ((li = malloc(sizeof(*li))) == NULL) {
689 err(STATUS_ERROR, "Cannot allocate %zu bytes",
693 SLIST_INSERT_HEAD(head, li, li_chain);
696 if (type != LT_CLASS)
697 li->li_number = (uid_t)strtol(sp, &ep, 0);
699 if (type != LT_CLASS && *ep == '\0') {
702 if (li->li_number == 0)
703 li->li_number = getpgrp();
706 if (li->li_number == 0)
707 li->li_number = getsid(mypid);
710 if (li->li_number < 0)
711 errx(STATUS_BADUSAGE,
712 "Negative jail ID `%s'", sp);
713 /* For compatibility with old -j */
714 if (li->li_number == 0)
715 li->li_number = -1; /* any jail */
718 if (li->li_number < 0)
719 errx(STATUS_BADUSAGE,
720 "Negative /dev/pts tty `%s'", sp);
721 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
723 if (stat(buf, &st) != -1)
726 errx(STATUS_BADUSAGE, "No such tty: `"
727 _PATH_DEV "pts/%s'", sp);
728 err(STATUS_ERROR, "Cannot access `"
729 _PATH_DEV "pts/%s'", sp);
739 if ((pw = getpwnam(sp)) == NULL)
740 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
741 li->li_number = pw->pw_uid;
744 if ((gr = getgrnam(sp)) == NULL)
745 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
746 li->li_number = gr->gr_gid;
749 if (strcmp(sp, "-") == 0) {
752 } else if (strcmp(sp, "co") == 0) {
758 snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
759 if (stat(buf, &st) != -1)
762 snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
763 if (stat(buf, &st) != -1)
767 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
768 err(STATUS_ERROR, "Cannot access `%s'", sp);
770 foundtty: if ((st.st_mode & S_IFCHR) == 0)
771 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
773 li->li_number = st.st_rdev;
778 if (strcmp(sp, "none") == 0)
780 else if (strcmp(sp, "any") == 0)
782 else if ((jid = jail_getid(sp)) != -1)
784 else if (*ep != '\0')
785 errx(STATUS_BADUSAGE,
786 "Invalid jail ID or name `%s'", sp);
791 li->li_name = strdup(sp);
792 if (li->li_name == NULL)
793 err(STATUS_ERROR, "Cannot allocate memory");
805 takepid(const char *pidfile, int pidfilelock)
807 char *endp, line[BUFSIZ];
811 fh = fopen(pidfile, "r");
813 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
817 * If we can lock pidfile, this means that daemon is not
818 * running, so would be better not to kill some random process.
820 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
822 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
824 if (errno != EWOULDBLOCK) {
826 "Error while locking file '%s'", pidfile);
831 if (fgets(line, sizeof(line), fh) == NULL) {
834 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
837 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
841 rval = strtol(line, &endp, 10);
842 if (*endp != '\0' && !isspace((unsigned char)*endp))
843 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
844 else if (rval < MIN_PID || rval > MAX_PID)
845 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);