#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <sched.h>

/* These are used as strings so that strcmp can be used as a delay loop */
char *s1, *s2;

/* 20000 is fine on my 333MHz Celeron. Adjust so that system time is not
   excessive */
#define DELAY 200000

void busy_wait(long sec, long usec)
{
	struct timeval tv;
	long long end_usec;
	gettimeofday(&tv,0);
	end_usec=(long long)(sec+tv.tv_sec)*1000000 + tv.tv_usec+usec;
	while (((long long)tv.tv_sec*1000000 + tv.tv_usec) < end_usec)
	{
		gettimeofday(&tv,0);
		strcmp(s1,s2); /* yuck */
	}
}

int main(int argc, char**argv)
{
	struct timespec st={10,50000000};
	int n=DELAY;
	int parent=1;

	if (argc<2) {fprintf(stderr,"Syntax: thud <children>\n"); return 0; }

	s1=malloc(n);
	s2=malloc(n);
	memset(s1,33,n);
	memset(s2,33,n);
	s1[n-1]=0;
	s2[n-1]=0;

	n=atoi(argv[1]);
	fprintf(stderr,"starting %d children\n",n);
	for (; n>0; n--)
		if (fork()==0) { sched_yield(); parent=0; break; }
	while (1)
	{
		nanosleep(&st, 0);
		if (parent) printf("running...");
		if (parent) fflush(stdout);
		busy_wait(6,0);
		if (parent) printf("done\n");
	}
	return 0;
}


