我们想在Linux平台下为我们的C程序添加一个计时器。
我们正在尝试发送数据包,我们想知道在1分钟内发送了多少数据包。我们希望定时器在正在执行发送数据包的while
循环的同时运行。例如:
while(1)
{
send packets;
}
此循环将继续发送数据包,直到按下ctrl-z。应该使用计时器在60秒后停止循环。
答案 0 :(得分:7)
你可以这样做:
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
volatile int stop=0;
void sigalrm_handler( int sig )
{
stop = 1;
}
int main(int argc, char **argv)
{
struct sigaction sact;
int num_sent = 0;
sigemptyset(&sact.sa_mask);
sact.sa_flags = 0;
sact.sa_handler = sigalrm_handler;
sigaction(SIGALRM, &sact, NULL);
alarm(60); /* Request SIGALRM in 60 seconds */
while (!stop) {
send_a_packet();
num_sent++;
}
printf("sent %d packets\n", num_sent);
exit(0);
}
如果循环开销过大,您可以通过每次迭代发送N个数据包并在每次迭代时将计数递增N来分摊开销。
答案 1 :(得分:5)
只需检查循环每次迭代的时间,并在1分钟过后,计算已发送的数据包数。
编辑已更改,以反映问题的实际要求!
time_t startTime = time(); // return current time in seconds
int numPackets = 0;
while (time() - startTime < 60)
{
send packet
numPackets++;
}
printf("Sent %d packets\n", numPackets);
答案 2 :(得分:4)
还可以检查此http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html以设置定时器,这些定时器将向您的进程发送信号,您可以停止while循环。
答案 3 :(得分:2)
查看标准time()
函数。
答案 4 :(得分:2)
以下是itimer的代码片段,可以在Linux平台上用于不同的时间间隔:
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
void timer_handler (int signum)
{
static int count = 0;
printf ("timer expired %d times\n", ++count);
}
int main ()
{
struct sigaction sa;
struct itimerval timer;
/* Install timer_handler as the signal handler for SIGVTALRM. */
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &timer_handler;
sigaction (SIGVTALRM, &sa, NULL);
/* Configure the timer to expire after 1 sec... */
timer.it_value.tv_sec = 1;
timer.it_value.tv_usec = 0;
/* ... and every 1000 msec after that. */
timer.it_interval.tv_sec = 1;
timer.it_interval.tv_usec = 0;
/* Start a virtual timer. It counts down whenever this process is
* executing. */
setitimer (ITIMER_VIRTUAL, &timer, NULL);
/* Do busy work. */
while (1);
sleep(1);
}
希望它会有所帮助。
答案 5 :(得分:0)
使用wheetimer(及其变体)数据结构来实现计时器。
答案 6 :(得分:-2)
NAME 睡眠 - 睡眠指定的秒数
概要 #include&lt; unistd.h&gt;
unsigned int sleep(unsigned int seconds);