Last active
December 27, 2015 10:49
-
-
Save zheplusplus/7313678 to your computer and use it in GitHub Desktop.
Keep a process running, and recover it after terminated. 我们不用很麻烦也能让一个进程持续跑起来.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
int main(int argc, char* argv[]) | |
{ | |
if (argc == 1) { | |
fprintf(stderr, "Usage:\n"); | |
fprintf(stderr, "keeprun prog arg0 arg1 ..."); | |
return 1; | |
} | |
while (1) { | |
int status = 0; | |
pid_t pid = fork(); | |
if (pid == -1) { | |
fprintf(stderr, "Fail to fork error"); | |
return 1; | |
} | |
if (pid == 0) { | |
return execv(argv[1], argv + 1); | |
} | |
waitpid(pid, &status, 0); | |
printf("Subprocess terminated, restart in 1 second"); | |
sleep(1); | |
} | |
} | |
/* Examples: | |
* keeprun `which python` some-script.py arg0 arg1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment