-
A Timed function in C
Hi folks,
I was wondering (while a program is running) how to make a specific codes/methods to run on a pre-defined time.
Lets say every 2 minutes this codes/methods ,inside the program, would be executed while the said program is still running.
I try searching about this topic through the net , but most of the decent result that I got is about creating a timer.
I'm Using MVC6 and my OS is Win2k.
The program waits for incomming messages of sort.And It (the codes/methods mentioned) has to be a part of the same program.
Any kind help, may it be psuedo code or links, will be much appreciated.
regards,
jaro
-
If you're reading messages from network sockets, you can use select() to observe the sockets, and have a timeout on the amout of time you spend waiting for something to happen
The pseudocode would be something like this
Code:
timeout = 2_mins;
while ( 1 ) {
n = select ( ..., timeout );
if ( message_received ) {
do_work();
// work out how long we waited for a message
// and how long it took to process it.
timeout = ?
} else
if ( timed_out ) {
do_timeout_code();
timeout = 2_mins;
}
}
Another alternative is to perhaps use threads, but that depends on how much interaction there is between the normal program and the timed program. If there is shared data, then access to that data will need protecting with semaphores and mutexes.
-
thanks Salem for the idea.
just one question though, I'm reading about select() and came across poll(). I'm just wondering what is the difference between the two.Base on my reading those two are the same or am I wrong?
regards,
Jaro
-
poll() and select() accomplish the same thing with different interfaces. One of poll()'s advantages is it doesn't clobber your input.
-
thanks cwr for your reply.
I've decided to use poll(). but I'm having a compiling error due to this part #include <sys/poll.h>.
I'm using MVC6 and it tells me that the #include <sys/poll.h> is not found.
I've found a sample code to work by in this site
poll() w/c tells me to include sys/poll.h.
I guess that those samples are for linux,but I really don't know.
I guess my question is , what header files should I include in order for me to use poll()?
Regards,
jaro
-
Just found out that poll() is a standard part of most Unix-like systems, but it's not a part of the C language (especially in windows system).
so I guess I'm using select().
tnx for all the people who responded to my question
-jaro