ubase/pidof.c

72 lines
1.1 KiB
C
Raw Normal View History

2013-08-29 10:11:26 +00:00
/* See LICENSE file for copyright and license details. */
#include <sys/types.h>
#include <dirent.h>
#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include "proc.h"
#include "util.h"
static void
usage(void)
{
2013-08-31 16:33:45 +00:00
eprintf("usage: %s [-s] [program...]\n", argv0);
2013-08-29 10:11:26 +00:00
}
int
main(int argc, char *argv[])
{
DIR *dp;
struct dirent *entry;
pid_t pid;
struct procstat ps;
2013-08-29 17:43:16 +00:00
char cmdline[BUFSIZ], *cmd, *p;
2013-08-29 10:11:26 +00:00
int i, found = 0;
2013-08-31 16:33:45 +00:00
int sflag = 0;
2013-08-29 10:11:26 +00:00
ARGBEGIN {
2013-08-31 16:33:45 +00:00
case 's':
sflag = 1;
break;
2013-08-29 10:11:26 +00:00
default:
usage();
} ARGEND;
if (!argc)
return 1;
if (!(dp = opendir("/proc")))
eprintf("opendir /proc:");
while ((entry = readdir(dp))) {
if (!pidfile(entry->d_name))
continue;
for (i = 0; i < argc; i++) {
pid = estrtol(entry->d_name, 10);
parsestat(pid, &ps);
if (parsecmdline(ps.pid, cmdline,
sizeof(cmdline)) < 0) {
cmd = ps.comm;
} else {
if ((p = strchr(cmdline, ' ')))
*p = '\0';
cmd = basename(cmdline);
}
if (strcmp(cmd, argv[i]) == 0) {
putword(entry->d_name);
found++;
2013-08-31 16:33:45 +00:00
if (sflag)
goto out;
2013-08-29 10:11:26 +00:00
}
}
}
2013-08-31 16:33:45 +00:00
out:
2013-08-29 10:11:26 +00:00
if (found)
putchar('\n');
closedir(dp);
return 0;
}