]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - bin/pkill/pkill.c
MFC r285340:
[FreeBSD/stable/8.git] / bin / pkill / pkill.c
1 /*      $NetBSD: pkill.c,v 1.16 2005/10/10 22:13:20 kleink Exp $        */
2
3 /*-
4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
5  * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Andrew Doran.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
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.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the NetBSD
22  *      Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #include <sys/types.h>
44 #include <sys/param.h>
45 #include <sys/sysctl.h>
46 #include <sys/proc.h>
47 #include <sys/queue.h>
48 #include <sys/stat.h>
49 #include <sys/time.h>
50 #include <sys/user.h>
51
52 #include <assert.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <limits.h>
56 #include <paths.h>
57 #include <string.h>
58 #include <unistd.h>
59 #include <signal.h>
60 #include <regex.h>
61 #include <ctype.h>
62 #include <fcntl.h>
63 #include <kvm.h>
64 #include <err.h>
65 #include <pwd.h>
66 #include <grp.h>
67 #include <errno.h>
68 #include <locale.h>
69
70 #define STATUS_MATCH    0
71 #define STATUS_NOMATCH  1
72 #define STATUS_BADUSAGE 2
73 #define STATUS_ERROR    3
74
75 #define MIN_PID 5
76 #define MAX_PID 99999
77
78 /* Ignore system-processes (if '-S' flag is not specified) and myself. */
79 #define PSKIP(kp)       ((kp)->ki_pid == mypid ||                       \
80                          (!kthreads && ((kp)->ki_flag & P_KTHREAD) != 0))
81
82 enum listtype {
83         LT_GENERIC,
84         LT_USER,
85         LT_GROUP,
86         LT_TTY,
87         LT_PGRP,
88         LT_JID,
89         LT_SID
90 };
91
92 struct list {
93         SLIST_ENTRY(list) li_chain;
94         long    li_number;
95 };
96
97 SLIST_HEAD(listhead, list);
98
99 static struct kinfo_proc *plist;
100 static char     *selected;
101 static const char *delim = "\n";
102 static int      nproc;
103 static int      pgrep;
104 static int      signum = SIGTERM;
105 static int      newest;
106 static int      oldest;
107 static int      interactive;
108 static int      inverse;
109 static int      longfmt;
110 static int      matchargs;
111 static int      fullmatch;
112 static int      kthreads;
113 static int      cflags = REG_EXTENDED;
114 static int      quiet;
115 static kvm_t    *kd;
116 static pid_t    mypid;
117
118 static struct listhead euidlist = SLIST_HEAD_INITIALIZER(euidlist);
119 static struct listhead ruidlist = SLIST_HEAD_INITIALIZER(ruidlist);
120 static struct listhead rgidlist = SLIST_HEAD_INITIALIZER(rgidlist);
121 static struct listhead pgrplist = SLIST_HEAD_INITIALIZER(pgrplist);
122 static struct listhead ppidlist = SLIST_HEAD_INITIALIZER(ppidlist);
123 static struct listhead tdevlist = SLIST_HEAD_INITIALIZER(tdevlist);
124 static struct listhead sidlist = SLIST_HEAD_INITIALIZER(sidlist);
125 static struct listhead jidlist = SLIST_HEAD_INITIALIZER(jidlist);
126
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);
132
133 int
134 main(int argc, char **argv)
135 {
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;
140         size_t jsz;
141         int (*action)(const struct kinfo_proc *);
142         struct kinfo_proc *kp;
143         struct list *li;
144         struct timeval best_tval;
145         regex_t reg;
146         regmatch_t regmatch;
147         pid_t pid;
148
149         setlocale(LC_ALL, "");
150
151         if (strcmp(getprogname(), "pgrep") == 0) {
152                 action = grepact;
153                 pgrep = 1;
154         } else {
155                 action = killact;
156                 p = argv[1];
157
158                 if (argc > 1 && p[0] == '-') {
159                         p++;
160                         i = (int)strtol(p, &q, 10);
161                         if (*q == '\0') {
162                                 signum = i;
163                                 argv++;
164                                 argc--;
165                         } else {
166                                 if (strncasecmp(p, "sig", 3) == 0)
167                                         p += 3;
168                                 for (i = 1; i < NSIG; i++)
169                                         if (strcasecmp(sys_signame[i], p) == 0)
170                                                 break;
171                                 if (i != NSIG) {
172                                         signum = i;
173                                         argv++;
174                                         argc--;
175                                 }
176                         }
177                 }
178         }
179
180         ancestors = 0;
181         criteria = 0;
182         debug_opt = 0;
183         pidfile = NULL;
184         pidfilelock = 0;
185         quiet = 0;
186         execf = NULL;
187         coref = _PATH_DEVNULL;
188
189         while ((ch = getopt(argc, argv, "DF:G:ILM:N:P:SU:ad:fg:ij:lnoqs:t:u:vx")) != -1)
190                 switch (ch) {
191                 case 'D':
192                         debug_opt++;
193                         break;
194                 case 'F':
195                         pidfile = optarg;
196                         criteria = 1;
197                         break;
198                 case 'G':
199                         makelist(&rgidlist, LT_GROUP, optarg);
200                         criteria = 1;
201                         break;
202                 case 'I':
203                         if (pgrep)
204                                 usage();
205                         interactive = 1;
206                         break;
207                 case 'L':
208                         pidfilelock = 1;
209                         break;
210                 case 'M':
211                         coref = optarg;
212                         break;
213                 case 'N':
214                         execf = optarg;
215                         break;
216                 case 'P':
217                         makelist(&ppidlist, LT_GENERIC, optarg);
218                         criteria = 1;
219                         break;
220                 case 'S':
221                         if (!pgrep)
222                                 usage();
223                         kthreads = 1;
224                         break;
225                 case 'U':
226                         makelist(&ruidlist, LT_USER, optarg);
227                         criteria = 1;
228                         break;
229                 case 'a':
230                         ancestors++;
231                         break;
232                 case 'd':
233                         if (!pgrep)
234                                 usage();
235                         delim = optarg;
236                         break;
237                 case 'f':
238                         matchargs = 1;
239                         break;
240                 case 'g':
241                         makelist(&pgrplist, LT_PGRP, optarg);
242                         criteria = 1;
243                         break;
244                 case 'i':
245                         cflags |= REG_ICASE;
246                         break;
247                 case 'j':
248                         makelist(&jidlist, LT_JID, optarg);
249                         criteria = 1;
250                         break;
251                 case 'l':
252                         longfmt = 1;
253                         break;
254                 case 'n':
255                         newest = 1;
256                         criteria = 1;
257                         break;
258                 case 'o':
259                         oldest = 1;
260                         criteria = 1;
261                         break;
262                 case 'q':
263                         if (!pgrep)
264                                 usage();
265                         quiet = 1;
266                         break;
267                 case 's':
268                         makelist(&sidlist, LT_SID, optarg);
269                         criteria = 1;
270                         break;
271                 case 't':
272                         makelist(&tdevlist, LT_TTY, optarg);
273                         criteria = 1;
274                         break;
275                 case 'u':
276                         makelist(&euidlist, LT_USER, optarg);
277                         criteria = 1;
278                         break;
279                 case 'v':
280                         inverse = 1;
281                         break;
282                 case 'x':
283                         fullmatch = 1;
284                         break;
285                 default:
286                         usage();
287                         /* NOTREACHED */
288                 }
289
290         argc -= optind;
291         argv += optind;
292         if (argc != 0)
293                 criteria = 1;
294         if (!criteria)
295                 usage();
296         if (newest && oldest)
297                 errx(STATUS_ERROR, "Options -n and -o are mutually exclusive");
298         if (pidfile != NULL)
299                 pidfromfile = takepid(pidfile, pidfilelock);
300         else {
301                 if (pidfilelock) {
302                         errx(STATUS_ERROR,
303                             "Option -L doesn't make sense without -F");
304                 }
305                 pidfromfile = -1;
306         }
307
308         mypid = getpid();
309
310         /*
311          * Retrieve the list of running processes from the kernel.
312          */
313         kd = kvm_openfiles(execf, coref, NULL, O_RDONLY, buf);
314         if (kd == NULL)
315                 errx(STATUS_ERROR, "Cannot open kernel files (%s)", buf);
316
317         /*
318          * Use KERN_PROC_PROC instead of KERN_PROC_ALL, since we
319          * just want processes and not individual kernel threads.
320          */
321         plist = kvm_getprocs(kd, KERN_PROC_PROC, 0, &nproc);
322         if (plist == NULL) {
323                 errx(STATUS_ERROR, "Cannot get process list (%s)",
324                     kvm_geterr(kd));
325         }
326
327         /*
328          * Allocate memory which will be used to keep track of the
329          * selection.
330          */
331         if ((selected = malloc(nproc)) == NULL) {
332                 err(STATUS_ERROR, "Cannot allocate memory for %d processes",
333                     nproc);
334         }
335         memset(selected, 0, nproc);
336
337         /*
338          * Refine the selection.
339          */
340         for (; *argv != NULL; argv++) {
341                 if ((rv = regcomp(&reg, *argv, cflags)) != 0) {
342                         regerror(rv, &reg, buf, sizeof(buf));
343                         errx(STATUS_BADUSAGE,
344                             "Cannot compile regular expression `%s' (%s)",
345                             *argv, buf);
346                 }
347
348                 for (i = 0, kp = plist; i < nproc; i++, kp++) {
349                         if (PSKIP(kp)) {
350                                 if (debug_opt > 0)
351                                     fprintf(stderr, "* Skipped %5d %3d %s\n",
352                                         kp->ki_pid, kp->ki_uid, kp->ki_comm);
353                                 continue;
354                         }
355
356                         if (matchargs &&
357                             (pargv = kvm_getargv(kd, kp, 0)) != NULL) {
358                                 jsz = 0;
359                                 while (jsz < sizeof(buf) && *pargv != NULL) {
360                                         jsz += snprintf(buf + jsz,
361                                             sizeof(buf) - jsz,
362                                             pargv[1] != NULL ? "%s " : "%s",
363                                             pargv[0]);
364                                         pargv++;
365                                 }
366                                 mstr = buf;
367                         } else
368                                 mstr = kp->ki_comm;
369
370                         rv = regexec(&reg, mstr, 1, &regmatch, 0);
371                         if (rv == 0) {
372                                 if (fullmatch) {
373                                         if (regmatch.rm_so == 0 &&
374                                             regmatch.rm_eo ==
375                                             (off_t)strlen(mstr))
376                                                 selected[i] = 1;
377                                 } else
378                                         selected[i] = 1;
379                         } else if (rv != REG_NOMATCH) {
380                                 regerror(rv, &reg, buf, sizeof(buf));
381                                 errx(STATUS_ERROR,
382                                     "Regular expression evaluation error (%s)",
383                                     buf);
384                         }
385                         if (debug_opt > 1) {
386                                 const char *rv_res = "NoMatch";
387                                 if (selected[i])
388                                         rv_res = "Matched";
389                                 fprintf(stderr, "* %s %5d %3d %s\n", rv_res,
390                                     kp->ki_pid, kp->ki_uid, mstr);
391                         }
392                 }
393
394                 regfree(&reg);
395         }
396
397         for (i = 0, kp = plist; i < nproc; i++, kp++) {
398                 if (PSKIP(kp))
399                         continue;
400
401                 if (pidfromfile >= 0 && kp->ki_pid != pidfromfile) {
402                         selected[i] = 0;
403                         continue;
404                 }
405
406                 SLIST_FOREACH(li, &ruidlist, li_chain)
407                         if (kp->ki_ruid == (uid_t)li->li_number)
408                                 break;
409                 if (SLIST_FIRST(&ruidlist) != NULL && li == NULL) {
410                         selected[i] = 0;
411                         continue;
412                 }
413
414                 SLIST_FOREACH(li, &rgidlist, li_chain)
415                         if (kp->ki_rgid == (gid_t)li->li_number)
416                                 break;
417                 if (SLIST_FIRST(&rgidlist) != NULL && li == NULL) {
418                         selected[i] = 0;
419                         continue;
420                 }
421
422                 SLIST_FOREACH(li, &euidlist, li_chain)
423                         if (kp->ki_uid == (uid_t)li->li_number)
424                                 break;
425                 if (SLIST_FIRST(&euidlist) != NULL && li == NULL) {
426                         selected[i] = 0;
427                         continue;
428                 }
429
430                 SLIST_FOREACH(li, &ppidlist, li_chain)
431                         if (kp->ki_ppid == (pid_t)li->li_number)
432                                 break;
433                 if (SLIST_FIRST(&ppidlist) != NULL && li == NULL) {
434                         selected[i] = 0;
435                         continue;
436                 }
437
438                 SLIST_FOREACH(li, &pgrplist, li_chain)
439                         if (kp->ki_pgid == (pid_t)li->li_number)
440                                 break;
441                 if (SLIST_FIRST(&pgrplist) != NULL && li == NULL) {
442                         selected[i] = 0;
443                         continue;
444                 }
445
446                 SLIST_FOREACH(li, &tdevlist, li_chain) {
447                         if (li->li_number == -1 &&
448                             (kp->ki_flag & P_CONTROLT) == 0)
449                                 break;
450                         if (kp->ki_tdev == (dev_t)li->li_number)
451                                 break;
452                 }
453                 if (SLIST_FIRST(&tdevlist) != NULL && li == NULL) {
454                         selected[i] = 0;
455                         continue;
456                 }
457
458                 SLIST_FOREACH(li, &sidlist, li_chain)
459                         if (kp->ki_sid == (pid_t)li->li_number)
460                                 break;
461                 if (SLIST_FIRST(&sidlist) != NULL && li == NULL) {
462                         selected[i] = 0;
463                         continue;
464                 }
465
466                 SLIST_FOREACH(li, &jidlist, li_chain) {
467                         /* A particular jail ID, including 0 (not in jail) */
468                         if (kp->ki_jid == (int)li->li_number)
469                                 break;
470                         /* Any jail */
471                         if (kp->ki_jid > 0 && li->li_number == -1)
472                                 break;
473                 }
474                 if (SLIST_FIRST(&jidlist) != NULL && li == NULL) {
475                         selected[i] = 0;
476                         continue;
477                 }
478
479                 if (argc == 0)
480                         selected[i] = 1;
481         }
482
483         if (!ancestors) {
484                 pid = mypid;
485                 while (pid) {
486                         for (i = 0, kp = plist; i < nproc; i++, kp++) {
487                                 if (PSKIP(kp))
488                                         continue;
489                                 if (kp->ki_pid == pid) {
490                                         selected[i] = 0;
491                                         pid = kp->ki_ppid;
492                                         break;
493                                 }
494                         }
495                         if (i == nproc) {
496                                 if (pid == mypid)
497                                         pid = getppid();
498                                 else
499                                         break;  /* Maybe we're in a jail ? */
500                         }
501                 }
502         }
503
504         if (newest || oldest) {
505                 best_tval.tv_sec = 0;
506                 best_tval.tv_usec = 0;
507                 bestidx = -1;
508
509                 for (i = 0, kp = plist; i < nproc; i++, kp++) {
510                         if (!selected[i])
511                                 continue;
512                         if (bestidx == -1) {
513                                 /* The first entry of the list which matched. */
514                                 ;
515                         } else if (timercmp(&kp->ki_start, &best_tval, >)) {
516                                 /* This entry is newer than previous "best". */
517                                 if (oldest)     /* but we want the oldest */
518                                         continue;
519                         } else {
520                                 /* This entry is older than previous "best". */
521                                 if (newest)     /* but we want the newest */
522                                         continue;
523                         }
524                         /* This entry is better than previous "best" entry. */
525                         best_tval.tv_sec = kp->ki_start.tv_sec;
526                         best_tval.tv_usec = kp->ki_start.tv_usec;
527                         bestidx = i;
528                 }
529
530                 memset(selected, 0, nproc);
531                 if (bestidx != -1)
532                         selected[bestidx] = 1;
533         }
534
535         /*
536          * Take the appropriate action for each matched process, if any.
537          */
538         did_action = 0;
539         for (i = 0, rv = 0, kp = plist; i < nproc; i++, kp++) {
540                 if (PSKIP(kp))
541                         continue;
542                 if (selected[i]) {
543                         if (longfmt && !pgrep) {
544                                 did_action = 1;
545                                 printf("kill -%d %d\n", signum, kp->ki_pid);
546                         }
547                         if (inverse)
548                                 continue;
549                 } else if (!inverse)
550                         continue;
551                 rv |= (*action)(kp);
552         }
553         if (!did_action && !pgrep && longfmt)
554                 fprintf(stderr,
555                     "No matching processes belonging to you were found\n");
556
557         exit(rv ? STATUS_MATCH : STATUS_NOMATCH);
558 }
559
560 static void
561 usage(void)
562 {
563         const char *ustr;
564
565         if (pgrep)
566                 ustr = "[-LSfilnoqvx] [-d delim]";
567         else
568                 ustr = "[-signal] [-ILfilnovx]";
569
570         fprintf(stderr,
571                 "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"
572                 "             [-P ppid] [-U uid] [-g pgrp] [-j jid] [-s sid]\n"
573                 "             [-t tty] [-u euid] pattern ...\n", getprogname(),
574                 ustr);
575
576         exit(STATUS_BADUSAGE);
577 }
578
579 static void
580 show_process(const struct kinfo_proc *kp)
581 {
582         char **argv;
583
584         if (quiet) {
585                 assert(pgrep);
586                 return;
587         }
588         if ((longfmt || !pgrep) && matchargs &&
589             (argv = kvm_getargv(kd, kp, 0)) != NULL) {
590                 printf("%d ", (int)kp->ki_pid);
591                 for (; *argv != NULL; argv++) {
592                         printf("%s", *argv);
593                         if (argv[1] != NULL)
594                                 putchar(' ');
595                 }
596         } else if (longfmt || !pgrep)
597                 printf("%d %s", (int)kp->ki_pid, kp->ki_comm);
598         else
599                 printf("%d", (int)kp->ki_pid);
600 }
601
602 static int
603 killact(const struct kinfo_proc *kp)
604 {
605         int ch, first;
606
607         if (interactive) {
608                 /*
609                  * Be careful, ask before killing.
610                  */
611                 printf("kill ");
612                 show_process(kp);
613                 printf("? ");
614                 fflush(stdout);
615                 first = ch = getchar();
616                 while (ch != '\n' && ch != EOF)
617                         ch = getchar();
618                 if (first != 'y' && first != 'Y')
619                         return (1);
620         }
621         if (kill(kp->ki_pid, signum) == -1) {
622                 /* 
623                  * Check for ESRCH, which indicates that the process
624                  * disappeared between us matching it and us
625                  * signalling it; don't issue a warning about it.
626                  */
627                 if (errno != ESRCH)
628                         warn("signalling pid %d", (int)kp->ki_pid);
629                 /*
630                  * Return 0 to indicate that the process should not be
631                  * considered a match, since we didn't actually get to
632                  * signal it.
633                  */
634                 return (0);
635         }
636         return (1);
637 }
638
639 static int
640 grepact(const struct kinfo_proc *kp)
641 {
642
643         show_process(kp);
644         if (!quiet)
645                 printf("%s", delim);
646         return (1);
647 }
648
649 static void
650 makelist(struct listhead *head, enum listtype type, char *src)
651 {
652         struct list *li;
653         struct passwd *pw;
654         struct group *gr;
655         struct stat st;
656         const char *cp;
657         char *sp, *ep, buf[MAXPATHLEN];
658         int empty;
659
660         empty = 1;
661
662         while ((sp = strsep(&src, ",")) != NULL) {
663                 if (*sp == '\0')
664                         usage();
665
666                 if ((li = malloc(sizeof(*li))) == NULL) {
667                         err(STATUS_ERROR, "Cannot allocate %zu bytes",
668                             sizeof(*li));
669                 }
670
671                 SLIST_INSERT_HEAD(head, li, li_chain);
672                 empty = 0;
673
674                 li->li_number = (uid_t)strtol(sp, &ep, 0);
675                 if (*ep == '\0') {
676                         switch (type) {
677                         case LT_PGRP:
678                                 if (li->li_number == 0)
679                                         li->li_number = getpgrp();
680                                 break;
681                         case LT_SID:
682                                 if (li->li_number == 0)
683                                         li->li_number = getsid(mypid);
684                                 break;
685                         case LT_JID:
686                                 if (li->li_number < 0)
687                                         errx(STATUS_BADUSAGE,
688                                              "Negative jail ID `%s'", sp);
689                                 /* For compatibility with old -j */
690                                 if (li->li_number == 0)
691                                         li->li_number = -1;     /* any jail */
692                                 break;
693                         case LT_TTY:
694                                 usage();
695                                 /* NOTREACHED */
696                         default:
697                                 break;
698                         }
699                         continue;
700                 }
701
702                 switch (type) {
703                 case LT_USER:
704                         if ((pw = getpwnam(sp)) == NULL)
705                                 errx(STATUS_BADUSAGE, "Unknown user `%s'", sp);
706                         li->li_number = pw->pw_uid;
707                         break;
708                 case LT_GROUP:
709                         if ((gr = getgrnam(sp)) == NULL)
710                                 errx(STATUS_BADUSAGE, "Unknown group `%s'", sp);
711                         li->li_number = gr->gr_gid;
712                         break;
713                 case LT_TTY:
714                         if (strcmp(sp, "-") == 0) {
715                                 li->li_number = -1;
716                                 break;
717                         } else if (strcmp(sp, "co") == 0) {
718                                 cp = "console";
719                         } else {
720                                 cp = sp;
721                         }
722
723                         snprintf(buf, sizeof(buf), _PATH_DEV "%s", cp);
724                         if (stat(buf, &st) != -1)
725                                 goto foundtty;
726
727                         snprintf(buf, sizeof(buf), _PATH_DEV "tty%s", cp);
728                         if (stat(buf, &st) != -1)
729                                 goto foundtty;
730
731                         if (errno == ENOENT)
732                                 errx(STATUS_BADUSAGE, "No such tty: `%s'", sp);
733                         err(STATUS_ERROR, "Cannot access `%s'", sp);
734
735 foundtty:               if ((st.st_mode & S_IFCHR) == 0)
736                                 errx(STATUS_BADUSAGE, "Not a tty: `%s'", sp);
737
738                         li->li_number = st.st_rdev;
739                         break;
740                 case LT_JID:
741                         if (strcmp(sp, "none") == 0)
742                                 li->li_number = 0;
743                         else if (strcmp(sp, "any") == 0)
744                                 li->li_number = -1;
745                         else if (*ep != '\0')
746                                 errx(STATUS_BADUSAGE,
747                                      "Invalid jail ID `%s'", sp);
748                         break;
749                 default:
750                         usage();
751                 }
752         }
753
754         if (empty)
755                 usage();
756 }
757
758 static int
759 takepid(const char *pidfile, int pidfilelock)
760 {
761         char *endp, line[BUFSIZ];
762         FILE *fh;
763         long rval;
764
765         fh = fopen(pidfile, "r");
766         if (fh == NULL)
767                 err(STATUS_ERROR, "Cannot open pidfile `%s'", pidfile);
768
769         if (pidfilelock) {
770                 /*
771                  * If we can lock pidfile, this means that daemon is not
772                  * running, so would be better not to kill some random process.
773                  */
774                 if (flock(fileno(fh), LOCK_EX | LOCK_NB) == 0) {
775                         (void)fclose(fh);
776                         errx(STATUS_ERROR, "File '%s' can be locked", pidfile);
777                 } else {
778                         if (errno != EWOULDBLOCK) {
779                                 errx(STATUS_ERROR,
780                                     "Error while locking file '%s'", pidfile);
781                         }
782                 }
783         }
784
785         if (fgets(line, sizeof(line), fh) == NULL) {
786                 if (feof(fh)) {
787                         (void)fclose(fh);
788                         errx(STATUS_ERROR, "Pidfile `%s' is empty", pidfile);
789                 }
790                 (void)fclose(fh);
791                 err(STATUS_ERROR, "Cannot read from pid file `%s'", pidfile);
792         }
793         (void)fclose(fh);
794
795         rval = strtol(line, &endp, 10);
796         if (*endp != '\0' && !isspace((unsigned char)*endp))
797                 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
798         else if (rval < MIN_PID || rval > MAX_PID)
799                 errx(STATUS_ERROR, "Invalid pid in file `%s'", pidfile);
800         return (rval);
801 }