From c4ff95798cd66d7c36789e58db83fc51d46442fc Mon Sep 17 00:00:00 2001 From: sin Date: Thu, 17 Apr 2014 14:00:36 +0100 Subject: [PATCH] Add respawn --- Makefile | 2 ++ respawn.1 | 12 ++++++++++++ respawn.c | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 respawn.1 create mode 100644 respawn.c diff --git a/Makefile b/Makefile index 05896d6..dd2f1cd 100644 --- a/Makefile +++ b/Makefile @@ -40,6 +40,7 @@ SRC = \ pidof.c \ pivot_root.c \ ps.c \ + respawn.c \ rmmod.c \ stat.c \ su.c \ @@ -67,6 +68,7 @@ MAN1 = \ pagesize.1 \ pidof.1 \ ps.1 \ + respawn.1 \ stat.1 \ su.1 \ truncate.1 \ diff --git a/respawn.1 b/respawn.1 new file mode 100644 index 0000000..f9d68a1 --- /dev/null +++ b/respawn.1 @@ -0,0 +1,12 @@ +.TH RESPAWN 1 ubase-VERSION +.SH NAME +\fBrespawn\fR - Spawn the given command repeatedly +.SH SYNOPSIS +\fBrespawn\fR [\fB-d\fI N\fR] \fIcmd\fR [\fIargs...\fR] +.SH DESCRIPTION +\fBrespawn\fR spawns the given \fIcmd\fR in a new session +repeatedly. +.SH OPTIONS +.TP +\fB-d\fR +Set the delay between invocations of \fIcmd\fR. It defaults to 0. diff --git a/respawn.c b/respawn.c new file mode 100644 index 0000000..c2aeea0 --- /dev/null +++ b/respawn.c @@ -0,0 +1,54 @@ +/* See LICENSE file for copyright and license details. */ +#include +#include +#include +#include +#include +#include "util.h" + +static void +usage(void) +{ + eprintf("usage: respawn [-d N] cmd [args...]\n"); +} + +int +main(int argc, char **argv) +{ + pid_t pid; + int savederrno; + unsigned int delay = 0; + + ARGBEGIN { + case 'd': + delay = estrtol(EARGF(usage()), 0); + break; + default: + usage(); + } ARGEND; + + if(argc < 1) + usage(); + + while (1) { + 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; + } + sleep(delay); + } + /* not reachable */ + return EXIT_SUCCESS; +}