我们想在Linux平台下为我们的C程序添加一个定时器。如何在c中实现一个计时器?
我们正在尝试发送数据包,我们想要知道在1分钟内发送了多少数据包。我们希望计时器与while
循环同时运行,以发送数据包正在执行。例如:
while(1)
{
send packets;
}
此循环将继续发送数据包,直到按下ctrl-z。计时器应该用于在60秒后停止循环。
我们想在Linux平台下为我们的C程序添加一个定时器。如何在c中实现一个计时器?
我们正在尝试发送数据包,我们想要知道在1分钟内发送了多少数据包。我们希望计时器与while
循环同时运行,以发送数据包正在执行。例如:
while(1)
{
send packets;
}
此循环将继续发送数据包,直到按下ctrl-z。计时器应该用于在60秒后停止循环。
人3睡眠:
名称 睡眠 - 睡眠指定的秒数
概要 的#include < unistd.h>中
unsigned int sleep(unsigned int seconds);
看那标准time()
功能。
也可以检查这个http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html设置定时器,它将发送信号给你的过程,你可以停止while循环。
只需检查循环的每次迭代的时间,当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);
你可以做这样的事情:
#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递增计数每次迭代分摊开销。
这里是itimer的代码片段,可以在Linux平台上使用不同的时间间隔在C:
#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);
}
希望这将有助于。
为什么不只是fork()并让子进程监视父进程? – AoeAoe 2012-04-17 12:50:15