#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>

#define BUCKET_SIZE 20
int bucket = 0;

//this is the signal handler that does the leak
void do_leak (int x) {

    if (bucket > 0)
	bucket--;
    printf ("Leaked... Current packets: %d\n", bucket);
    alarm (1);
}

int main () {

    int r;

    srandom (time(NULL));

    signal (SIGALRM, do_leak);
    alarm(1);

    printf ("Press the enter key (repeatedly) to send random number of packets:\n");

    while (1) {
	scanf ("%*c");
	r = random ()%4+1; //send 1-4 packets at a time, randomly
	
	bucket += r;
	if (bucket > BUCKET_SIZE) {
	    printf ("Overflow. %d packet(s) dropped.\n", bucket-BUCKET_SIZE);
	    bucket = BUCKET_SIZE;
	}
	printf ("Current number of packets: %d\n", bucket);
    }

    return 0;
}

