我发布了这个答案来说明一种与“显而易见”的方法完全不同的方法,希望有人发现它正是他们所需要的。没想到竟然被选为最佳答案!谨慎对待这个解决方案,因为存在潜在的危险和并发问题......
您可以使用setitimer()系统调用在指定的毫秒数后将 SIGALRM(警报信号)发送到您的程序。信号是异步事件(有点像消息),它会中断正在执行的程序以让信号处理程序运行。
当您的程序开始时,操作系统会安装一组默认信号处理程序,但您可以使用sigaction()安装自定义信号处理程序。
所以你只需要一个线程;使用全局变量,以便信号处理程序可以访问必要的信息并发送新数据包或根据需要重复上一个数据包。
这是一个对您有利的示例:
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
int ticker = 0;
void timerTick(int dummy)
{
printf("The value of ticker is: %d\n", ticker);
}
int main()
{
int i;
struct sigaction action;
struct itimerval time;
//Here is where we specify the SIGALRM handler
action.sa_handler = &timerTick;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
//Register the handler for SIGALRM
sigaction(SIGALRM, &action, NULL);
time.it_interval.tv_sec = 1; //Timing interval in seconds
time.it_interval.tv_usec = 000000; //and microseconds
time.it_value.tv_sec = 0; //Initial timer value in seconds
time.it_value.tv_usec = 1; //and microseconds
//Set off the timer
setitimer(ITIMER_REAL, &time, NULL);
//Be busy
while(1)
for(ticker = 0; ticker < 1000; ticker++)
for(i = 0; i < 60000000; i++)
;
}