Skip to content

Instantly share code, notes, and snippets.

@fferri
Created February 18, 2016 15:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fferri/0a3138d15d96744d3680 to your computer and use it in GitHub Desktop.
Save fferri/0a3138d15d96744d3680 to your computer and use it in GitHub Desktop.
execv with timeout
#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