From 5a48a98dc9200bd442a84b225029189aecd06657 Mon Sep 17 00:00:00 2001 From: Tom Moguljak Date: Wed, 11 Oct 2023 10:56:50 +0200 Subject: [PATCH] Ajout Exo2 TP4 --- TP4/Exo2/helpers.c | 19 +++++++++++++++++ TP4/Exo2/helpers.h | 7 ++++++ TP4/Exo2/mytimeout.c | 51 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 TP4/Exo2/helpers.c create mode 100644 TP4/Exo2/helpers.h create mode 100644 TP4/Exo2/mytimeout.c diff --git a/TP4/Exo2/helpers.c b/TP4/Exo2/helpers.c new file mode 100644 index 0000000..718fe40 --- /dev/null +++ b/TP4/Exo2/helpers.c @@ -0,0 +1,19 @@ +#include "helpers.h" +#include +#include + +int set_signal_handler(int signo, void (*handler)(int)) { + struct sigaction sa; + sa.sa_handler = handler; // call `handler` on signal + sigemptyset(&sa.sa_mask); // don't block other signals in handler + sa.sa_flags = SA_RESTART; // restart system calls + return sigaction(signo, &sa, NULL); +} + +double tstamp(void) { + struct timespec tv; + clock_gettime(CLOCK_REALTIME, &tv); + return tv.tv_sec + tv.tv_nsec * 1.0e-9; +} + + diff --git a/TP4/Exo2/helpers.h b/TP4/Exo2/helpers.h new file mode 100644 index 0000000..2084c6a --- /dev/null +++ b/TP4/Exo2/helpers.h @@ -0,0 +1,7 @@ +#ifndef _HELPERS_H +#define _HELPERS_H + +int set_signal_handler(int signo, void (*handler)(int)); +double tstamp(void); + +#endif diff --git a/TP4/Exo2/mytimeout.c b/TP4/Exo2/mytimeout.c new file mode 100644 index 0000000..0751703 --- /dev/null +++ b/TP4/Exo2/mytimeout.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include +#include +#include +#include "helpers.c" +#include "helpers.h" + +#define BUF_SIZE 256 + +void kill_son(int) +{ + if (waitpid(-1, NULL, WNOHANG) == 0) + { + kill(0, SIGTERM); + } + else + exit(0); +} +int main(int argc, char **argv) +{ + char *args[argc - 1]; + int secondes = (int)strtod(argv[1], NULL); + pid_t p; + if (argc < 3) + { + printf("Usage : %s [arg]", argv[0]); + return EXIT_FAILURE; + } + for (int i = 2; i < argc; i++) + { + args[i - 2] = argv[i]; + } + args[argc - 2] = NULL; + p = fork(); + switch (p) + { + case 0: + execvp(argv[2], args); + exit(0); + case -1: + exit(EXIT_FAILURE); + default: + alarm(secondes); + set_signal_handler(SIGALRM, &kill_son); + sleep(secondes); + } + exit(0); +} \ No newline at end of file