ubase/respawn.c

114 lines
1.9 KiB
C
Raw Normal View History

2014-04-17 13:00:36 +00:00
/* See LICENSE file for copyright and license details. */
#include <sys/stat.h>
2014-06-30 18:03:41 +00:00
#include <sys/time.h>
2014-04-17 13:00:36 +00:00
#include <sys/types.h>
#include <sys/wait.h>
2014-06-30 18:03:41 +00:00
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
2014-06-30 18:03:41 +00:00
#include <stdio.h>
#include <stdlib.h>
2014-04-17 13:00:36 +00:00
#include <unistd.h>
2014-06-30 18:03:41 +00:00
2014-04-17 13:00:36 +00:00
#include "util.h"
static void
sigterm(int sig)
{
if (sig == SIGTERM) {
kill(0, SIGTERM);
2014-10-02 22:45:25 +00:00
_exit(0);
}
}
2014-04-17 13:00:36 +00:00
static void
usage(void)
{
eprintf("usage: %s [-l fifo] [-d N] cmd [args...]\n", argv0);
2014-04-17 13:00:36 +00:00
}
int
2014-04-18 10:34:02 +00:00
main(int argc, char *argv[])
2014-04-17 13:00:36 +00:00
{
char *fifo = NULL;
unsigned int delay = 0;
2014-04-17 13:00:36 +00:00
pid_t pid;
char buf[BUFSIZ];
2014-04-17 13:00:36 +00:00
int savederrno;
ssize_t n;
struct pollfd pollset[1];
int polln;
2014-04-17 13:00:36 +00:00
ARGBEGIN {
case 'd':
delay = estrtol(EARGF(usage()), 0);
break;
case 'l':
fifo = EARGF(usage());
break;
2014-04-17 13:00:36 +00:00
default:
usage();
} ARGEND;
2014-07-09 15:39:32 +00:00
if (argc < 1)
2014-04-17 13:00:36 +00:00
usage();
if (fifo && delay > 0)
usage();
2014-07-06 20:35:35 +00:00
setsid();
signal(SIGTERM, sigterm);
if (fifo) {
pollset->fd = open(fifo, O_RDONLY | O_NONBLOCK);
if (pollset->fd < 0)
eprintf("open %s:", fifo);
pollset->events = POLLIN;
}
2014-04-17 13:00:36 +00:00
while (1) {
if (fifo) {
pollset->revents = 0;
polln = poll(pollset, 1, -1);
if (polln <= 0) {
if (polln == 0 || errno == EAGAIN)
continue;
eprintf("poll:");
}
while ((n = read(pollset->fd, buf, sizeof(buf))) > 0)
;
if (n < 0)
if (errno != EAGAIN)
eprintf("read %s:", fifo);
if (n == 0) {
close(pollset->fd);
pollset->fd = open(fifo, O_RDONLY | O_NONBLOCK);
if (pollset->fd < 0)
eprintf("open %s:", fifo);
pollset->events = POLLIN;
}
}
2014-04-17 13:00:36 +00:00
pid = fork();
if (pid < 0)
eprintf("fork:");
switch (pid) {
case 0:
execvp(argv[0], argv);
savederrno = errno;
weprintf("execvp %s:", argv[0]);
_exit(savederrno == ENOENT ? 127 : 126);
break;
default:
waitpid(pid, NULL, 0);
break;
}
if (!fifo)
sleep(delay);
2014-04-17 13:00:36 +00:00
}
/* not reachable */
2014-10-02 22:45:25 +00:00
return 0;
2014-04-17 13:00:36 +00:00
}