C/UNIX Execute a function once every x milliseconds
How do I execute a function once every 1000 milliseconds using alarm() or sleep? I want the program to do something else if the function does not execute or complete in 1000 milliseconds.
EDIT: a开发者_Python百科dded Pseudocode
while(true) {
alarm(1000);
execute function;
sleep(1000);
alarm(0);
}
Now if alarm(1000) signals SIGALRM is this where I could call the other function? I'm new to this sort of stuff so not even sure if I am using it right.
How crisp is the requirement, ie, how much jitter can you tolerate?
What version of UNIX?
Basically, if this is a hard deadline -- it sounds like one -- you're going to need to do some special stuff, because basic UNIX isn't really a hard-real-time system.
Let's assume for the moment that you mean Linux. You'll want to
- use nice(2) to raise the process priority
- use a fine-grained timer, as with ualarm(3)
That will probably do. If you need finer grained, or more predictable, timing, then you probably need to write a kernel extension to it can be driven with a kernel timer. (Solaris has some improved support for hard-real-time, but it's still not really a hard real-time system.)
Life will get considerably easier if you can use a real-time Linux or UNIX. Here's a list of some options. Here's an article you might find usefui.
Update
You should also look at nanosleep(2) or setitimer(2). Notice that all of these say the interval is at least the one in the argument. If you have a hard deadline, you need to wait for somewhat less than the actual interval and then figure out what to do with any change on your thousand millisecs.
I have used this function on Linux to "sleep" in milliseconds:
void Sleep(unsigned int milliSeconds)
{
struct timespec req = {0};
time_t seconds = (int) (milliSeconds / 1000);
milliSeconds = milliSeconds - (seconds * 1000);
req.tv_sec = seconds;
req.tv_nsec = milliSeconds * 1000000L;
while (nanosleep(&req, &req) == -1)
continue;
}
while (1) {
sleep(1);
/* Act */
}
If you need tighter delays, the normal way to do it is to call select() with no fds and a low timeout.
精彩评论