2013-07-14 20:12:22 -07:00
|
|
|
/* pending.c - reusable stuff awaiting review
|
|
|
|
*
|
|
|
|
* new lib entries for stuff in toys/pending
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "toys.h"
|
|
|
|
|
|
|
|
// Execute a callback for each PID that matches a process name from a list.
|
2013-09-11 10:09:53 -07:00
|
|
|
void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
|
2013-07-14 20:12:22 -07:00
|
|
|
{
|
|
|
|
DIR *dp;
|
|
|
|
struct dirent *entry;
|
|
|
|
|
|
|
|
if (!(dp = opendir("/proc"))) perror_exit("opendir");
|
|
|
|
|
|
|
|
while ((entry = readdir(dp))) {
|
2013-09-03 16:43:32 -07:00
|
|
|
unsigned u;
|
|
|
|
char *cmd, **curname;
|
2013-07-14 20:12:22 -07:00
|
|
|
|
2013-09-03 16:43:32 -07:00
|
|
|
if (!(u = atoi(entry->d_name))) continue;
|
|
|
|
sprintf(libbuf, "/proc/%u/cmdline", u);
|
|
|
|
if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
|
2013-07-14 20:12:22 -07:00
|
|
|
|
|
|
|
for (curname = names; *curname; curname++)
|
2013-09-11 10:09:53 -07:00
|
|
|
if (**curname == '/' ? !strcmp(cmd, *curname)
|
|
|
|
: !strcmp(basename(cmd), basename(*curname)))
|
|
|
|
if (callback(u, *curname)) break;
|
2013-09-03 16:43:32 -07:00
|
|
|
if (*curname) break;
|
2013-07-14 20:12:22 -07:00
|
|
|
}
|
|
|
|
closedir(dp);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* used to get the interger value.
|
|
|
|
*/
|
2013-09-06 10:21:28 -07:00
|
|
|
unsigned long get_int_value(const char *numstr, unsigned long lowrange, unsigned long highrange)
|
2013-07-14 20:12:22 -07:00
|
|
|
{
|
|
|
|
unsigned long rvalue = 0;
|
|
|
|
char *ptr;
|
2013-09-09 23:01:35 -07:00
|
|
|
|
|
|
|
if (!isdigit(*numstr)) perror_exit("bad number '%s'", numstr);
|
2013-07-14 20:12:22 -07:00
|
|
|
errno = 0;
|
|
|
|
rvalue = strtoul(numstr, &ptr, 10);
|
|
|
|
|
2013-09-09 23:01:35 -07:00
|
|
|
if (errno || numstr == ptr || *ptr || rvalue < lowrange || rvalue > highrange)
|
|
|
|
perror_exit("bad number '%s'", numstr);
|
2013-07-14 20:12:22 -07:00
|
|
|
|
2013-09-09 23:01:35 -07:00
|
|
|
return rvalue;
|
2013-07-14 20:12:22 -07:00
|
|
|
}
|
2013-08-10 11:18:18 -07:00
|
|
|
|
|
|
|
void daemonize(void)
|
|
|
|
{
|
|
|
|
int fd = open("/dev/null", O_RDWR);
|
|
|
|
if (fd < 0) fd = xcreate("/", O_RDONLY, 0666);
|
|
|
|
|
|
|
|
pid_t pid = fork();
|
|
|
|
if (pid < 0) perror_exit("DAEMON: failed to fork");
|
|
|
|
if (pid) exit(EXIT_SUCCESS);
|
|
|
|
|
|
|
|
setsid();
|
|
|
|
dup2(fd, 0);
|
|
|
|
dup2(fd, 1);
|
|
|
|
dup2(fd, 2);
|
|
|
|
if (fd > 2) close(fd);
|
|
|
|
}
|