ubase/respawn.c

107 lines
1.7 KiB
C
Raw Normal View History

2014-04-17 13:00:36 +00:00
/* See LICENSE file for copyright and license details. */
#include <sys/select.h>
#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 <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;
int fd;
ssize_t n;
fd_set rdfd;
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) {
2014-09-28 17:35:55 +00:00
/* TODO: we should use O_RDONLY and re-open the fd on EOF */
fd = open(fifo, O_RDWR | O_NONBLOCK);
if (fd < 0)
eprintf("open %s:", fifo);
}
2014-04-17 13:00:36 +00:00
while (1) {
if (fifo) {
FD_ZERO(&rdfd);
FD_SET(fd, &rdfd);
n = select(fd + 1, &rdfd, NULL, NULL, NULL);
if (n < 0)
eprintf("select:");
if (n == 0 || FD_ISSET(fd, &rdfd) == 0)
continue;
while ((n = read(fd, buf, sizeof(buf))) > 0)
;
if (n < 0)
if (errno != EAGAIN)
eprintf("read %s:", fifo);
}
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
}