ubase/respawn.c

94 lines
1.5 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 <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
usage(void)
{
eprintf("usage: respawn [-l fifo] [-d N] cmd [args...]\n");
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;
if(argc < 1)
usage();
if (fifo && delay > 0)
usage();
if (fifo) {
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:
if (setsid() < 0)
eprintf("setsid:");
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 */
return EXIT_SUCCESS;
}