http://perforce.freebsd.org/chv.cgi?CH=72975 Change 72975 by pjd@pjd_anger on 2005/03/12 15:51:12 Add '-o' option which allows to select the oldest of the matching processes. This option exists in Solaris and Linux. Affected files ... .. //depot/user/pjd/pkill/usr.bin/pkill/pkill.1#7 edit .. //depot/user/pjd/pkill/usr.bin/pkill/pkill.c#9 edit Differences ... ==== //depot/user/pjd/pkill/usr.bin/pkill/pkill.1#7 (text+ko) ==== @@ -147,7 +147,9 @@ .Nm pgrep command. .It Fl n -Match only the most recently created process, if any. +Select only the newest (most recently started) of the matching processes. +.It Fl o +Select only the oldest (least recently started) of the matching processes. .It Fl s Ar sid Restrict matches to processes with a session ID in the comma-separated list ==== //depot/user/pjd/pkill/usr.bin/pkill/pkill.c#9 (text+ko) ==== @@ -99,6 +99,7 @@ int pgrep; int signum = SIGTERM; int newest; +int oldest; int inverse; int longfmt; int matchargs; @@ -132,12 +133,11 @@ char buf[_POSIX2_LINE_MAX], *mstr, **pargv, *p, *q; const char *execf, *coref; int debug_opt; - int i, ch, bestidx, rv, criteria, pidfromfile; + int i, ch, rv, criteria, pidfromfile; size_t jsz; void (*action)(struct kinfo_proc *); struct kinfo_proc *kp; struct list *li; - struct timeval best_tval; regex_t reg; regmatch_t regmatch; @@ -177,7 +177,7 @@ pidfromfile = -1; execf = coref = _PATH_DEVNULL; - while ((ch = getopt(argc, argv, "DF:G:M:N:P:SU:d:fg:ij:lns:t:u:vx")) != -1) + while ((ch = getopt(argc, argv, "DF:G:M:N:P:SU:d:fg:ij:lnos:t:u:vx")) != -1) switch (ch) { case 'D': debug_opt++; @@ -237,6 +237,10 @@ newest = 1; criteria = 1; break; + case 'o': + oldest = 1; + criteria = 1; + break; case 's': makelist(&sidlist, LT_SID, optarg); criteria = 1; @@ -266,6 +270,8 @@ criteria = 1; if (!criteria) usage(); + if (newest && oldest) + errx(STATUS_ERROR, "-n and -o are mutually exclusive"); mypid = getpid(); @@ -434,23 +440,29 @@ selected[i] = 1; } - if (newest) { + if (newest || oldest) { + struct timeval best_tval; + int bestidx; + best_tval.tv_sec = 0; best_tval.tv_usec = 0; bestidx = -1; +#define PNEWER(kp) ((kp)->ki_start.tv_sec > best_tval.tv_sec || \ + ((kp)->ki_start.tv_sec == best_tval.tv_sec && \ + (kp)->ki_start.tv_usec > best_tval.tv_usec)) for (i = 0, kp = plist; i < nproc; i++, kp++) { if (!selected[i]) continue; - - if (kp->ki_start.tv_sec > best_tval.tv_sec || - (kp->ki_start.tv_sec == best_tval.tv_sec - && kp->ki_start.tv_usec > best_tval.tv_usec)) { + if (bestidx == -1 || + (newest && PNEWER(kp)) || + (oldest && !PNEWER(kp))) { best_tval.tv_sec = kp->ki_start.tv_sec; best_tval.tv_usec = kp->ki_start.tv_usec; bestidx = i; } } +#undef PNEWER memset(selected, 0, nproc); if (bestidx != -1) @@ -481,9 +493,9 @@ const char *ustr; if (pgrep) - ustr = "[-Sfilnvx] [-d delim]"; + ustr = "[-Sfilnovx] [-d delim]"; else - ustr = "[-signal] [-finvx]"; + ustr = "[-signal] [-finovx]"; fprintf(stderr, "usage: %s %s [-F pidfile] [-G gid] [-M core] [-N system]\n"