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
67 #define MAX_PID PID_MAX
69 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
70 #define PSKIP(kp) ((kp)->kp_pid == mypid || \
71 (!kthreads && (kp)->kp_pid <= 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, *tdev;
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:STU:ac:d:fg:ij:lnoqs:t:u:vx")) != -1) {
193 makelist(&rgidlist, LT_GROUP, optarg);
211 makelist(&ppidlist, LT_GENERIC, optarg);
222 err(STATUS_ERROR, "Not a terminal");
223 if ((tdev = strdup(tdev)) == NULL)
224 err(STATUS_ERROR, "Cannot allocate memory");
225 makelist(&tdevlist, LT_TTY, tdev);
229 makelist(&ruidlist, LT_USER, optarg);
236 makelist(&classlist, LT_CLASS, optarg);
248 makelist(&pgrplist, LT_PGRP, optarg);
255 makelist(&jidlist, LT_JID, optarg);
275 makelist(&sidlist, LT_SID, optarg);
279 makelist(&tdevlist, LT_TTY, optarg);
283 makelist(&euidlist, LT_USER, optarg);
304 if (newest && oldest)
305 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
307 pidfromfile = takepid(pidfile, pidfilelock);
311 "Option -L doesn't make sense without -F");
319 * Retrieve the list of running processes from the kernel.
321 kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
323 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
325 if (pidfromfile >= 0)
326 plist = kvm_getprocs(kd, KERN_PROC_PID, pidfromfile, &nproc);
328 plist = kvm_getprocs(kd, KERN_PROC_ALL, 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->kp_pid, kp->kp_uid, kp->kp_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->kp_pid, kp->kp_uid, mstr);
404 for (i = 0, kp = plist; i < nproc; i++, kp++) {
408 if (pidfromfile >= 0 && kp->kp_pid != pidfromfile) {
413 SLIST_FOREACH(li, &ruidlist, li_chain)
414 if (kp->kp_ruid == (uid_t)li->li_number)
416 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
421 SLIST_FOREACH(li, &rgidlist, li_chain)
422 if (kp->kp_rgid == (gid_t)li->li_number)
424 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
429 SLIST_FOREACH(li, &euidlist, li_chain)
430 if (kp->kp_uid == (uid_t)li->li_number)
432 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
437 SLIST_FOREACH(li, &ppidlist, li_chain)
438 if (kp->kp_ppid == (pid_t)li->li_number)
440 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
445 SLIST_FOREACH(li, &pgrplist, li_chain)
446 if (kp->kp_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->kp_flags & P_CONTROLT) == 0)
457 if (kp->kp_tdev == (dev_t)li->li_number)
460 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
465 SLIST_FOREACH(li, &sidlist, li_chain)
466 if (kp->kp_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->kp_jailid == (int)li->li_number)
478 if (kp->kp_jailid > 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->kp_flags & P_SYSTEM) == 0)
493 if (SLIST_FIRST(&classlist) != NULL && li == NULL) {
505 for (i = 0, kp = plist; i < nproc; i++, kp++) {
508 if (kp->kp_pid == pid) {
518 break; /* Maybe we're in a jail ? */
523 if (newest || oldest) {
524 best_tval.tv_sec = 0;
525 best_tval.tv_usec = 0;
528 for (i = 0, kp = plist; i < nproc; i++, kp++) {
532 /* The first entry of the list which matched. */
534 } else if (timercmp(&kp->kp_start, &best_tval, >)) {
535 /* This entry is newer than previous "best". */
536 if (oldest) /* but we want the oldest */
539 /* This entry is older than previous "best". */
540 if (newest) /* but we want the newest */
543 /* This entry is better than previous "best" entry. */
544 best_tval.tv_sec = kp->kp_start.tv_sec;
545 best_tval.tv_usec = kp->kp_start.tv_usec;
549 memset(selected, 0, nproc);
551 selected[bestidx] = 1;
555 * Take the appropriate action for each matched process, if any.
558 for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
562 if (longfmt && !pgrep) {
564 printf("kill -%d %d\n", signum, kp->kp_pid);
572 if (!did_action && !pgrep && longfmt)
574 "No matching processes belonging to you were found\n");
576 exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
585 ustr = "[-LSTfilnoqvx] [-d delim]";
587 ustr = "[-signal] [-ILTfilnovx]";
590 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
591 " [-P ppid] [-U uid] [-c class] [-g pgrp] [-j jid]\n"
592 " [-s sid] [-t tty] [-u euid] pattern ...\n",
593 getprogname(), ustr);
595 exit(STATUS_BADUSAGE);
599 show_process(const struct kinfo_proc *kp)
607 if ((longfmt || !pgrep) && matchargs &&
608 (argv = kvm_getargv(kd, kp, 0)) != NULL) {
609 printf("%d ", (int)kp->kp_pid);
610 for (; *argv != NULL; argv++) {
615 } else if (longfmt || !pgrep)
616 printf("%d %s", (int)kp->kp_pid, kp->kp_comm);
618 printf("%d", (int)kp->kp_pid);
622 killact(const struct kinfo_proc *kp)
628 * Be careful, ask before killing.
634 first = ch = getchar();
635 while (ch != '\n' && ch != EOF)
637 if (first != 'y' && first != 'Y')
640 if (kill(kp->kp_pid, signum) == -1) {
642 * Check for ESRCH, which indicates that the process
643 * disappeared between us matching it and us
644 * signalling it; don't issue a warning about it.
647 warn("signalling pid %d", (int)kp->kp_pid);
649 * Return 0 to indicate that the process should not be
650 * considered a match, since we didn't actually get to
659 grepact(const struct kinfo_proc *kp)
669 makelist(struct listhead *head, enum listtype type, char *src)
676 char *sp, *ep, buf[MAXPATHLEN];
681 while ((sp = strsep(&src, ",")) != NULL) {
685 if ((li = malloc(sizeof(*li))) == NULL) {
686 err(STATUS_ERROR, "Cannot allocate %zu bytes",
690 SLIST_INSERT_HEAD(head, li, li_chain);
693 if (type != LT_CLASS)
694 li->li_number = (uid_t)strtol(sp, &ep, 0);
696 if (type != LT_CLASS && *ep == '\0') {
699 if (li->li_number == 0)
700 li->li_number = getpgrp();
703 if (li->li_number == 0)
704 li->li_number = getsid(mypid);
707 if (li->li_number < 0)
708 errx(STATUS_BADUSAGE,
709 "Negative jail ID `%s'", sp);
710 /* For compatibility with old -j */
711 if (li->li_number == 0)
712 li->li_number = -1; /* any jail */
715 if (li->li_number < 0)
716 errx(STATUS_BADUSAGE,
717 "Negative /dev/pts tty `%s'", sp);
718 snprintf(buf, sizeof(buf), _PATH_DEV "pts/%s",
720 if (stat(buf, &st) != -1)
723 errx(STATUS_BADUSAGE, "No such tty: `"
724 _PATH_DEV "pts/%s'", sp);
725 err(STATUS_ERROR, "Cannot access `"
726 _PATH_DEV "pts/%s'", sp);
736 if ((pw = getpwnam(sp)) == NULL)
737 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
738 li->li_number = pw->pw_uid;
741 if ((gr = getgrnam(sp)) == NULL)
742 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
743 li->li_number = gr->gr_gid;
746 if (strcmp(sp, "-") == 0) {
749 } else if (strcmp(sp, "co") == 0) {
755 if (strncmp(cp, _PATH_DEV, sizeof(_PATH_DEV)-1) == 0 &&
756 stat(cp, &st) != -1) {
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;
778 if (strcmp(sp, "none") == 0)
780 else if (strcmp(sp, "any") == 0)
782 else if (*ep != '\0')
783 errx(STATUS_BADUSAGE,
784 "Invalid jail ID `%s'", sp);
788 li->li_name = strdup(sp);
789 if (li->li_name == NULL)
790 err(STATUS_ERROR, "Cannot allocate memory");
802 takepid(const char *pidfile, int pidfilelock)
804 char *endp, line[BUFSIZ];
808 fh = fopen(pidfile, "r");
810 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
814 * If we can lock pidfile, this means that daemon is not
815 * running, so would be better not to kill some random process.
817 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
819 errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
821 if (errno != EWOULDBLOCK) {
823 "Error while locking file '%s'", pidfile);
828 if (fgets(line, sizeof(line), fh) == NULL) {
831 errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
834 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
838 rval = strtol(line, &endp, 10);
839 if (*endp != '\0' && !isspace((unsigned char)*endp))
840 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
841 else if (rval < MIN_PID || rval > MAX_PID)
842 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);