首页 技术 正文
技术 2022年11月14日
0 收藏 332 点赞 4,973 浏览 1930 个字
setitimer()为Linux的API,并非C语言的Standard Library,setitimer()有两个功能,
一是指定一段时间后,才执行某个function,二是每间格一段时间就执行某个function,
以下程序demo如何使用setitimer()。/*
setitimer 原函数声明
Filename : timer.cpp
Compiler : gcc 4.1.0 on Fedora Core 5
Description : setitimer() set the interval to run function
Synopsis : #include <sys/time.h>
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue);
struct itimerval {
struct timerval it_interval;
struct timerval it_value;
};
struct timeval {
long tv_sec;
long tv_usec;
}
Release : 11/25/2006
*/ #include <stdio.h> // for printf()
#include <unistd.h> // for pause()
#include <signal.h> // for signal()
#include <string.h> // for memset()
#include <sys/time.h> // struct itimeral. setitimer() void printMsg(int); int main() {
// Get system call result to determine successful or failed
int res = ;
// Register printMsg to SIGALRM
signal(SIGALRM, printMsg);
struct itimerval tick;
// Initialize struct
memset(&tick, , sizeof(tick));
// Timeout to run function first time
tick.it_value.tv_sec = ; // sec
tick.it_value.tv_usec = ; // micro sec.
// Interval time to run function
tick.it_interval.tv_sec = ;
tick.it_interval.tv_usec = ;
// Set timer, ITIMER_REAL : real-time to decrease timer,
// send SIGALRM when timeout
res = setitimer(ITIMER_REAL, &tick, NULL);
if (res) {
printf("Set timer failed!!/n");
}
// Always sleep to catch SIGALRM signal
while() {
pause();
}
return ; } void printMsg(int num) {
printf("%s","Hello World!!\n");
} 当setitimer()所执行的timer时间到了,会呼叫SIGALRM signal,所以在第35行用signal()将要执行的function指定给SIGALRM。
在第47行呼叫setitimer()设定timer,但setitimer()第二个参数是sturct,负责设定timeout时间,所以第36行到第44行设定
此struct。itimerval.it_value设定第一次执行function所延迟的秒数, itimerval.it_interval设定以后每几秒执行function,
所以若只想延迟一段时间执行function,只要设定 itimerval.it_value即可,若要设定间格一段时间就执行function,则it_value
和it_interval都要设定,否则 funtion的第一次无法执行,就别说以后的间隔执行了。
第40行和第43行的tv_sec为sec,第41行和44行为micro sec(0.001 sec)。
第47行的第一个参数ITIMER_REAL,表示以real-time方式减少timer,在timeout时会送出SIGALRM signal。第三个参数会存放
旧的timeout值,如果不需要的话,指定NULL即可。
第53行的pause(),命令系统进入sleep状态,等待任何signal,一定要用while()无穷循环执行pause(),如此才能一直接收
SIGALRM signal以间隔执行function,若拿掉while(),则function只会执行一次而已。
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774