Skip to content

Instantly share code, notes, and snippets.

@dhilst
Created February 2, 2016 15:59
Show Gist options
  • Save dhilst/f65ce9d7e14052df2912 to your computer and use it in GitHub Desktop.
Save dhilst/f65ce9d7e14052df2912 to your computer and use it in GitHub Desktop.
respawn - a small utility to respawn process that exists when should keep up.
CFLAGS_respawn += -Wall
respawn: respawn.c
$(CC) $(CFLAGS_$@) $(LDFLAGS_$@) $(CFLAGS) $(LDFLAGS) -o $@ $<
clean:
rm -f respawn
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/wait.h>
#define log(fmt, args...) syslog(LOG_MAKEPRI(LOG_USER, LOG_INFO), fmt, ##args)
int main(int argc, char **argv)
{
openlog("respawn", LOG_PERROR, 0);
int rc = daemon(0, 0);
if (rc) {
log("daemon failed %d/%s", errno, strerror(errno));
closelog();
return -1;
}
while (1) {
log("Starting %s", argv[1]);
pid_t pid = fork();
if (pid == 0) { /* child */
return execvp(argv[1], &argv[1]);
} else if (pid > 0) { /* parent */
int chldstatus;
pid_t chldpid = waitpid(pid, &chldstatus, 0);
if (chldpid == pid) { /* waitpid success */
if (WIFEXITED(chldstatus)) {
log("%s exited, respawing", argv[1]);
log("%s status: %d", argv[1], chldstatus);
}
continue;
}
} else { /* error */
log("fork error %d/%s", errno, strerror(errno));
return -1;
}
}
closelog();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment