Ajout de l'exo 1 TP4
This commit is contained in:
19
TP4/Exo1/helpers.c
Normal file
19
TP4/Exo1/helpers.c
Normal 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/Exo1/helpers.h
Normal file
7
TP4/Exo1/helpers.h
Normal file
@@ -0,0 +1,7 @@
|
||||
#ifndef _HELPERS_H
|
||||
#define _HELPERS_H
|
||||
|
||||
int set_signal_handler(int signo, void (*handler)(int));
|
||||
double tstamp(void);
|
||||
|
||||
#endif
|
67
TP4/Exo1/pi.c
Normal file
67
TP4/Exo1/pi.c
Normal file
@@ -0,0 +1,67 @@
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <assert.h>
|
||||
#include "helpers.h"
|
||||
#include "helpers.c"
|
||||
|
||||
uint64_t shots = 0,
|
||||
shots_in = 0;
|
||||
|
||||
double pi = 0,
|
||||
t1;
|
||||
|
||||
void alarm_handler(int)
|
||||
{
|
||||
printf("pi = %f\n", pi);
|
||||
printf("le nombre de tirs est de %f\n", (double)shots);
|
||||
alarm(5);
|
||||
}
|
||||
|
||||
void int_handler(int)
|
||||
{
|
||||
char c;
|
||||
|
||||
alarm(0);
|
||||
printf("Voulez-vous quitter ? (y/n)\n");
|
||||
c = getchar();
|
||||
|
||||
if (c == 'y' || c == 'Y')
|
||||
{
|
||||
printf("Le temps écoulé est de %f\n", tstamp() - t1);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
alarm(5);
|
||||
}
|
||||
|
||||
void quit_handler(int)
|
||||
{
|
||||
shots = 0;
|
||||
shots_in = 0;
|
||||
t1 = tstamp();
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
double x, y;
|
||||
t1 = tstamp();
|
||||
alarm(5);
|
||||
set_signal_handler(SIGALRM, &alarm_handler);
|
||||
set_signal_handler(SIGINT, &int_handler);
|
||||
set_signal_handler(SIGQUIT, &quit_handler);
|
||||
|
||||
while (1)
|
||||
{
|
||||
x = ((double)rand()) / (double)RAND_MAX;
|
||||
y = ((double)rand()) / (double)RAND_MAX;
|
||||
shots++;
|
||||
|
||||
if ((x * x + y * y) <= 1)
|
||||
shots_in++;
|
||||
|
||||
pi = 4 * (double)(shots_in) / shots;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user