Last active
February 7, 2017 10:17
-
-
Save BOOtak/a4ce16a17d4150c78cf20b92399ec5ae to your computer and use it in GitHub Desktop.
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 <stdbool.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
#define TIMEOUT 1 | |
#define EXIT_STATUS_SUCCESS 0 | |
#define EXIT_STATUS_FAILED 1 | |
#define EXIT_STATUS_TIMEOUT 2 | |
static void timeout_func() | |
{ | |
printf("Child process ended by timeout.\n"); | |
exit(EXIT_STATUS_TIMEOUT); | |
} | |
static void set_timer(sighandler_t func, time_t value_sec) | |
{ | |
signal(SIGALRM, func); | |
struct itimerval new_t; | |
new_t.it_value.tv_sec = value_sec; | |
new_t.it_value.tv_usec = 0; | |
new_t.it_interval.tv_sec = 0; | |
new_t.it_interval.tv_usec = 0; | |
setitimer(ITIMER_REAL, &new_t, NULL); | |
} | |
#define RUN_IN_ANOTHER_PROCESS_WITH_TIMEOUT(func, timeout, exit_code) do { \ | |
pid_t pid = fork(); \ | |
if (pid == 0) { \ | |
set_timer(timeout_func, timeout); \ | |
if (func) { \ | |
exit(EXIT_STATUS_SUCCESS); \ | |
} \ | |
exit(EXIT_STATUS_FAILED); \ | |
} else if (pid == -1) { \ | |
printf("Unable to fork: %s!\n", strerror(errno)); \ | |
} else { \ | |
int status; \ | |
waitpid(pid, &status, 0); \ | |
exit_code = WEXITSTATUS(status); \ | |
} \ | |
} while (false) | |
int some_function(const char* param, int other_param) | |
{ | |
printf("param: \"%s\", int is %x\n", param, other_param); | |
return 1; | |
} | |
int other_func(int param) | |
{ | |
printf("param-pam-pam: %x\n", param); | |
return 0; | |
} | |
int third_func() | |
{ | |
while (1) | |
{ | |
} | |
return 0; | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
int exit_code; | |
RUN_IN_ANOTHER_PROCESS_WITH_TIMEOUT(some_function("Hello", 0x7357), TIMEOUT, exit_code); | |
printf("process1 exited with %d.\n", exit_code); | |
RUN_IN_ANOTHER_PROCESS_WITH_TIMEOUT(other_func(0x7537), TIMEOUT, exit_code); | |
printf("process2 exited with %d.\n", exit_code); | |
RUN_IN_ANOTHER_PROCESS_WITH_TIMEOUT(third_func(), TIMEOUT, exit_code); | |
printf("process3 exited with %d.\n", exit_code); | |
return 0; | |
} | |
// shell@S307:/data/local/tmp $ ./run | |
// param: "Hello", int is 7357 | |
// process1 exited with 0. | |
// param-pam-pam: 7537 | |
// process2 exited with 1. | |
// Child process ended by timeout. | |
// process3 exited with 2. | |
// shell@S307:/data/local/tmp $ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment