r305_dm/TP4/Exo1/pi.c

85 lines
1.5 KiB
C
Raw Permalink Normal View History

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