: How do I implement a sleep in a C program that is less than
: 1 second? The sleep() call takes an unsigned int as a parameter.
: Basically I have a program that needs to do something every 1/2 second, yet
: I can't have this process eating up CPU time while waiting for the time
: to elapse. I have thought about alarms, or signals, but how would you
: implement them to do this?
I can only speak for HP-UX (which is the kind of Unix we have running
here).
Basically, sleep() does nothing else than call alarm() and pause(). Both
sleep() and alarm() take integer arguments, so you are out of luck here.
HP-UX also supports interval timers, which can be accessed with
getitimer(2) and setitimer(2). These timers can be used to count real-time,
process virtual time or when profiling a process. Each of these "timer
modes" delivers a different signal after the timer expires. The example in
the man page describes how to set a timer in 0.5 seconds intervals.
The manual page for alarm(2) also says "On systems that support the
getitimer() and setitimer() system calls...", which means that these calls
are not available on every system. But if you are using your own company's
products, you shouldn't have any problems... ;-)
Hope that helps,
MfG
HH
PS: Oh, about using signals: You simply have to set up a signal-catching
routine using the signal(2) system call. Upon receipt of the specified
signal, this routine is executed. So you have to look up the manual for
setitimer, check what type of signal is delivered by the timer mode you
want, and register a C function for this signal. Then you set the timer and
do something else or (more likely) suspend the process with pause(). When
the timer expires, the signal is sent to the process, the pause() is
terminated and the signal handling routine is called. Beware: Some systems
require the process to re-install the signal handling routine each time it
was called. So the first thing the function should do is register itself
again with signal() (only if you want to do the same thing again, of course).
--
- Institute of Computer Graphics | Tel. +43 1 58801 4107 -
- Vienna University of Technology | http://eiunix.tuwien.ac.at/~heinz -