r305_dm/TP4/Exo2/mytimeout.c

51 lines
999 B
C
Raw Permalink Normal View History

2023-10-11 10:56:50 +02:00
#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);
}