Link to home
Start Free TrialLog in
Avatar of danny762
danny762

asked on

Timer in C

Dear All,

 I want to write a program in Cwhich calls a function mip() every 10 sec. But I don`t want to use any infinite loop for this. I want to use timers in C.

 consider the following program:

 main()
 {
   mip();
 }

 I want mip() function to be called every 10 seconds using a timer. Please help me how to do. explaining code using timer is appreciated.

with regards,
Danny.
 
Avatar of Axter
Axter
Flag of United States of America image

Hi danny762,
What is your OS, and what compiler are you using?


Cheers!
Avatar of danny762
danny762

ASKER

I am using Suse Linux 9.1 and gcc

Danny.
Hi danny762,

> I don`t want to use any infinite loop
How else do you want to keep the program running?

#include <unistd.h>
void main()
{
  while (27)
  {
     sleep (10);
     mip();
  }
}

======
Werner
No Werner, I don`t want to use like this, I want to set a timer which calls mip() for every 10 seconds. If I do like what you  said then when it goes for sleep I can`t do anything just simply sleeping for 10 seconds. I want to do some other things in this 10 seconds.

Danny.

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Danny,

jkr's solution is quite sound.  You might also investigate multi-threading / multi-tasking.  One logic path would be free to perform whatever the application requires while the other thread / task waits for the timer to complete.


Kent
>. But I don`t want to use any infinite loop for this.

Obviously , you need to run the process in background (&).
This code is compiled on HP unix 11i


#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#define T_DURATION      2
void time_out ();

void time_out ()
{
    char sendByte_l;


   printf("Inside timer func\n");
   signal(SIGALRM, time_out);
   alarm(0);
   alarm(T_DURATION);

}



void main()
{
      alarm(T_DURATION);
      signal(SIGALRM, time_out);
      //call your function mip() here
      sleep(10);      
}

Please remove sleep from the above function . This was put for testing. You need to ensure that your mip() function doesnot terminate before 10ms. It should run in an infinite loop ideally. then after 10sec timer function will be called.

This code is compiled on HP unix 11i


#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#define T_DURATION     2
void time_out ();

void time_out ()
{
    char sendByte_l;


   printf("Inside timer func\n");
   signal(SIGALRM, time_out);
   alarm(0);
   alarm(T_DURATION);

}



void main()
{
     alarm(T_DURATION);
     signal(SIGALRM, time_out);
     //call your function mip() here
}