Ajout Exo2 TP4

This commit is contained in:
Tom MOGULJAK 2023-10-11 10:56:50 +02:00
parent c971482d73
commit 5a48a98dc9
3 changed files with 77 additions and 0 deletions

19
TP4/Exo2/helpers.c Normal file
View File

@ -0,0 +1,19 @@
#include "helpers.h"
#include <signal.h>
#include <time.h>
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;
}

7
TP4/Exo2/helpers.h Normal file
View File

@ -0,0 +1,7 @@
#ifndef _HELPERS_H
#define _HELPERS_H
int set_signal_handler(int signo, void (*handler)(int));
double tstamp(void);
#endif

51
TP4/Exo2/mytimeout.c Normal file
View File

@ -0,0 +1,51 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#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 <nbsec> <com> [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);
}