/* getclock.c -- Program that determines time required for a fork */
/*               If calls getclock before and after a fork in the child */
/*               and prints the time interval between the two times in  */
/*               milliseconds.                                          */
/*               Compile with                                           */
/*                          gcc getclock.c -lrt                         */
/*               getclock, clock_getres work on my digital unix but not */
/*               on my linux [to be checked further since getclock is a */
/*               standard C function!] */


#include <stdio.h>
#include <time.h>
#include <sys/timers.h>
#define  MAXTIMES  100
#define  SLEEPTIME 2

int main(){
  struct timespec time[2];
  int clktyp = TIMEOFDAY;
  int pid;
  int lcv;

  if (clock_getres(clktyp, &(time[0])) < 0) {
    perror("clock_getres");
    exit(1);}
  printf("The clock resolution is %d seconds, %d nanoseconds\n\n", 
	 time[0].tv_sec,time[0].tv_nsec);

  for (lcv=0; lcv < MAXTIMES; lcv++) {
    if (getclock(clktyp, &(time[0])) != 0) {
      perror("getclock");
      exit(1);}
    if((pid = fork()) < 0) { /* error */
      perror("fork");
      exit(1);
    } else if (pid == 0) {   /* child */
      if (getclock(clktyp, &(time[1])) != 0) {
	perror("getclock");
	exit(1);}
      if (time[0].tv_sec == time[1].tv_sec) 
	printf("DELTA = %d milliseconds\n", 
	       (time[1].tv_nsec - time[0].tv_nsec)/1000000);
      else
	printf("DELTA = %d milliseconds\n", 
	       (((long)999999999)+time[1].tv_nsec - time[0].tv_nsec)/1000000);
      exit(0);
    } else {                 /* parent */
      sleep(SLEEPTIME);
    }
  }
}
