r305_dm/TP4/Exo1/pi.c
2023-10-11 11:00:11 +02:00

85 lines
1.5 KiB
C

#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;
sigset_t alset, intset, quitset;
void alarm_handler(int)
{
sigprocmask(SIG_BLOCK, &alset, NULL);
printf("pi = %f\n", pi);
printf("le nombre de tirs est de %f\n", (double)shots);
alarm(5);
sigprocmask(SIG_UNBLOCK, &alset, NULL);
}
void int_handler(int)
{
alarm(0);
sigprocmask(SIG_BLOCK, &intset, NULL);
char c;
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);
}
return;
sigprocmask(SIG_UNBLOCK, &intset, NULL);
alarm(5);
}
void quit_handler(int)
{
alarm(0);
sigprocmask(SIG_BLOCK, &quitset, NULL);
shots = 0;
shots_in = 0;
t1 = tstamp();
sigprocmask(SIG_UNBLOCK, &quitset, NULL);
alarm(5);
}
int main(int argc, char *argv[])
{
double x, y;
t1 = tstamp();
alarm(5);
sigaddset(&alset, SIGINT);
sigaddset(&alset, SIGQUIT);
sigaddset(&intset, SIGALRM);
sigaddset(&intset, SIGQUIT);
sigaddset(&quitset, SIGALRM);
sigaddset(&quitset, SIGINT);
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;
}
}