Created
February 18, 2016 15:16
-
-
Save fferri/0a3138d15d96744d3680 to your computer and use it in GitHub Desktop.
execv with timeout
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 <sys/types.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
#include <string.h> | |
void exec_with_timeout(char * const *argv, int timeout, int kill_signal = SIGKILL) | |
{ | |
pid_t intermediate_pid = fork(); | |
if(intermediate_pid == 0) { | |
pid_t worker_pid = fork(); | |
if(worker_pid == 0) { | |
execv(argv[0], argv); | |
_exit(0); | |
} | |
pid_t timeout_pid = fork(); | |
if(timeout_pid == 0) { | |
sleep(timeout); | |
_exit(0); | |
} | |
pid_t exited_pid = wait(NULL); | |
if(exited_pid == worker_pid) { | |
kill(timeout_pid, SIGKILL); | |
} else { | |
kill(worker_pid, kill_signal); | |
} | |
wait(NULL); // Collect the other process | |
_exit(0); // Or some more informative status | |
} | |
waitpid(intermediate_pid, 0, 0); | |
} | |
int main() | |
{ | |
char * argv[1]; | |
argv[0] = strdup("/path/to/long_proces"); | |
exec_with_timeout(argv, 6); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment