How to implement a timer in c?

c, linux

Solution

You could do something like this:

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

volatile int stop=0;

void sigalrm_handler( int sig )
{
    stop = 1;
}

int main(int argc, char **argv)
{
    struct sigaction sact;
    int num_sent = 0;
    sigemptyset(&sact.sa_mask);
    sact.sa_flags = 0;
    sact.sa_handler = sigalrm_handler;
    sigaction(SIGALRM, &sact, NULL);

    alarm(60);  /* Request SIGALRM in 60 seconds */
    while (!stop) {
        send_a_packet();
        num_sent++;
    }

    printf("sent %d packets\n", num_sent);
    exit(0);
}

If loop overhead turns out to be excessive, you could amortize the overhead by sending N packets per iteration and incrementing the count by N each iteration.

Problem

We want to add a timer to our C program under Linux platform. We are trying to send the packets and we want to find out how many packets get sent in 1 minute. We want the timer to run at the same time as the `while` loop for sending the packet is being executed. For example: ``` while(1) { send packets; } ``` This loop will keep on sending the packets until ctrl-z is pressed. The timer should be used to stop the loop after 60 seconds.

Original source