How to implement polling for a function using timer in C?

Hi,

Can you please help me in implementing a timer based polling for function in C? ie. the function should be called in say 30secs(when 30secs has lapsed).

Thanks

Use alarm(2) to set an alarm for 30 sec. When the timer runs out, a SIGALRM will be sent to your process. Catch that signal, do what you want, then set the alarm(2) again. Keep doing ad infinitum.

Suppose if I have put the alarm in a function, and i need to catch the signal only inside the function, is it possible? ie. the process should be executing in the normal manner till it reaches this function and catches the signal.

The two APIs designed for this are "select" (BSD) and "poll" (SYSV).

signal driven IO (SIGIO or SIGALRM) is very rarely used and hard to get right.

Then the modern approach is using select or poll in a thread.

Is there any apprach apart from using threads since I have not worked with threads at all.

Depends what it's supposed to fit in.

If you are writing a program from scratch then there is no problem with

main()
{
     while (1)
     {
          sleep(30);
          doCheck();
     }
}

If it's an Xt based client application then use one of the timer callback functions.

It all depends what framework it has to work in.

This has to be implemented in a deamon process in UNIX system. The daemon waits for any messages in a message queue and parallely has to go and execute a function by polling in every 30secs.

What sort of message queue, a UNIX fifo?

I recommend that you have a loop which sits reading the fifo and uses SIGALRM to break the read of the fifo. When you get the alarm it should then give you EINTR for the read, you then go and do your every second work in that occurs.

Then, set the alarm again and go back to reading the fifo.

If you are using MQseries then that has timeouts on the MQGET anyway.