Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <sched.h>
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <unistd.h>
- #include <wait.h>
- sig_atomic_t timeout = 0, exit_code = 2, chld = 0;
- void sigchld_handler(int signum)
- {
- chld = 1;
- }
- void sigalarm_handler(int signum)
- {
- timeout = 1;
- }
- void set_handler(int signum, void* handler, struct sigaction* action)
- {
- action->sa_handler = handler;
- action->sa_flags = SA_RESTART;
- sigaction(signum, action, NULL);
- }
- struct sigaction sigalarm_action, sigchld_action;
- int main(int argc, char* argv[])
- {
- pid_t pid = fork();
- if (pid == -1) {
- printf("%s\n", "signaled");
- return 1;
- }
- if (pid == 0) {
- execvp(argv[2], &argv[2]);
- exit(1);
- } else {
- int sleep_amount = atoi(argv[1]);
- set_handler(SIGALRM, sigalarm_handler, &sigalarm_action);
- set_handler(SIGCHLD, sigchld_handler, &sigchld_action);
- alarm(sleep_amount);
- sigset_t important_mask;
- sigfillset(&important_mask);
- sigdelset(&important_mask, SIGALRM);
- sigdelset(&important_mask, SIGCHLD);
- int exit_status;
- sigsuspend(&important_mask);
- if (!timeout) {
- waitpid(pid, &exit_status, 0);
- if (WIFSIGNALED(exit_status)) {
- exit_code = 1;
- printf("%s\n", "signaled");
- } else {
- printf("%s\n", "ok");
- exit_code = 0;
- }
- } else {
- kill(pid, SIGKILL);
- exit_code = 2;
- waitpid(pid, &exit_status, 0);
- printf("%s\n", "timeout");
- }
- return exit_code;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement