1. Call the alarm function using Signal SIGALRM No. 14th
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include < Signal.h>void handle (int signum) {printf ("hello\n");} int main (int argc, const char *argv[]) { signal (SIGALRM, handle); while (1) { alarm (3); Sleep (3); } return 0;}
Sends a SIGALRM signal to itself every 3 seconds, signal calls handle for processing after receiving SIGALRM signal
--"alarm can only be accurate to seconds.
2.setitimer is also processed by sending a signal to itself, but can be accurate to the ACME level
int Setitimer (int which, const struct Itimerval *new_value,
struct Itimerval *old_value);
Itimer_real decrements in REAL time, and delivers sigalrm upon expiration.
Itimer_virtual decrements only if the process is executing, and delivers
SIGVTALRM upon expiration.
itimer_prof decrements Both when the process executes and then the system is
&NBSP;&NBSP;&NBSP;&N bsp; executing on behalf of the process. coupled with itimer_vir-
tual, this timer is usually used to profiles the time spent by
the application in user and Kernel space. sigprof is delivered
upon expiration.
struct Itimerval {
struct Timeval it_interval; /* Next Value */
struct Timeval it_value; /* Current Value */
};
struct Timeval {
Long tv_sec; /* seconds */
Long tv_usec; /* microseconds */
};
--"3 modes produce different signals in 3, using similar methods
3.timerfd_create Timerfd_settime---set FD readable by time and then invoke the handler function via select polling
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/timerfd.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #define ERR_EXIT (m) Do {perror (M); Exit (Exit_failure); }while (0) int main (int argc, const char *argv[]) {struct ITIMERSPEC time; Time.it_value.tv_sec = 5; Time.it_interval.tv_sec = 2; int timerfd = timerfd_create (clock_realtime, 0); if (TIMERFD = =-1) err_exit ("Timerfd_create"); if (Timerfd_settime (TIMERFD, 0, &time, NULL) = =-1) err_exit ("Timerfd_settime"); Fd_set Read1, ready; Fd_zero (&READ1); Fd_set (TIMERFD, &read1); Char buf[1024]; struct Timeval time_select; while (1) {time_select.tv_sec = 3;//must be defined in while internal time_select.tv_usec = 11; Ready = Read1; int nready = SELECT (Timerfd + 1, &ready, NULL, NULL, &time_select);//set to block if (Nready =-1) ERr_exit ("select"); else if (Nready = = 0) printf ("timeout"); else {if ( -1 = = Read (TIMERFD, buf, sizeof buf)) {printf ("%s\n", Strerror (Errn o);//Print error message Err_exit ("read"); } printf ("come\n"); }} return 0;}
4. Directly using select--accurate to millisecond level
int Mssleep (Long ms) { struct timeval TV; tv.tv_sec = 0; Tv.tv_usec = ms; Return Select (0, NULL, NULL, NULL, &TV);}
Other information:
Http://www.cppblog.com/CppExplore/archive/2008/04/02/46111.html
Using Timers in Linux