Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a timer in c?

Tags:

c

linux

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.

like image 393
Sowmya Msk Avatar asked Apr 17 '12 10:04

Sowmya Msk


People also ask

Is there a timer function in C?

You can't have timers in pure standard C. You need some operating system support. On Linux, read time(7) carefully.


2 Answers

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.

like image 67
Lance Richardson Avatar answered Oct 11 '22 22:10

Lance Richardson


Just check the time on every iteration of the loop and when 1 minute has elapsed, count how many packets you have sent.

Edit changed to reflect what the question actually asks!

time_t startTime = time(); // return current time in seconds
int numPackets = 0;
while (time() - startTime < 60)
{
    send packet
    numPackets++;
}
printf("Sent %d packets\n", numPackets);
like image 21
JeremyP Avatar answered Oct 11 '22 22:10

JeremyP