/* ---------------------------------------------------------------- */ /* PROGRAM sig-3.c */ /* This program uses the alarm clock to sample the value of a */ /* global counter in fixed periods. */ /* ---------------------------------------------------------------- */ #include #include unsigned long counter; /* global counter */ int MAX; /* max # of sampling */ int ALARMcount; /* sampling count */ int SECOND; /* sampling duration */ /* ---------------------------------------------------------------- */ /* FUNCTION ALARMhandler() : */ /* This is the alarm signal handler. When it is activated, this */ /* function increases the sampling count, displays the current */ /* value of the global counter, and resets both the counter and */ /* sampling duration. */ /* ---------------------------------------------------------------- */ void ALARMhandler(int sig) { signal(SIGALRM, SIG_IGN); /* ignore this signal */ ALARMcount++; /* one more sampling */ printf("*** ALARMhandler --> alarm received no. %d.\n", ALARMcount); printf("*** ALARMhandler --> counter = %ld\n", counter); printf("*** ALARMhandler --> alarm reset to %d seconds\n", SECOND); if (ALARMcount == MAX) { /* if max. count, exit */ printf("*** ALARMhandler --> Maximum alarm count reached. exit\n"); exit(0); } counter = 0; /* otherwise, reset counter */ alarm(SECOND); /* set alarm for next run */ signal(SIGALRM, ALARMhandler); /* reinstall the handler */ } /* ---------------------------------------------------------------- */ /* the main program starts here */ /* ---------------------------------------------------------------- */ void main(int argc, char *argv[]) { if (argc != 3) { printf("Use: %s seconds max-alarm-count\n", argv[0]); printf("No. of seconds is set to 1\n"); SECOND = 1; printf("Max number of alarms set to 5\n"); MAX = 5; } else { SECOND = atoi(argv[1]); MAX = atoi(argv[2]); } counter = 0; /* clear global counter */ ALARMcount = 0; /* clear sampling counter */ signal(SIGALRM,ALARMhandler); /* set alarm signal handler */ printf("Alarm set to %d seconds and is ticking now.....\n", SECOND); alarm(SECOND); /* set alarm clock */ while (1) /* now, just keep adding 1 */ counter++; }