created sep dirs for hw/labs, write lab 5
[assignments.git] / assgn7 / timer.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4
5 #include <signal.h>
6 #include <time.h>
7
8 struct timespec *start_time, *stop_time;
9 int done;
10
11 void handle_start() {
12
13 if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, start_time) == -1) {
14
15 printf("failed to get start time.\n");
16 exit(1);
17 }
18 }
19
20 void handle_stop() {
21
22 long int start_sec, stop_sec, delta;
23
24 if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID, stop_time) == -1) {
25
26 printf("failed to get stop time.\n");
27 exit(1);
28 }
29
30 start_sec = ((long int) start_time->tv_nsec);
31 stop_sec = ((long int) stop_time->tv_nsec);
32
33 delta = stop_sec - start_sec;
34
35 printf("%ld nanoseconds elapsed between signals.\n", delta);
36
37 done = 1;
38 }
39
40 int main(int argc, char *argv[]) {
41
42 done = 0;
43
44 start_time = (struct timespec *) calloc(1, sizeof(struct timespec));
45 stop_time = (struct timespec *) calloc(1, sizeof(struct timespec));
46
47 if(signal(SIGTSTP, handle_start) == SIG_ERR ||
48 signal(SIGCONT, handle_stop) == SIG_ERR) {
49
50 printf("could not bind signal handlers\n");
51 return 1;
52 }
53
54 terminate_check:
55
56 pause();
57
58 if(!done)
59 goto terminate_check; /* sorry */
60
61 free(start_time);
62 free(stop_time);
63
64 return 0;
65 }