该程序发送UDP消息,并在超时前等待回复。我用select来控制超时。但是,我不知道为什么局部变量“total_latency”会在while循环中重置。
“ * ** * ** * *** total_latency”和“^^^ ^^^^^^^^^^^^^^^^ total_latency“显示正确的结果。但是“##################### total_latency”总是显示0。似乎重置了该值。有没有人对此有所了解?是由于select()?
输出:
############### total_latency:0.000发送UDP Ping 0 ....
等待UDP Ping echo ....
延迟[0]:2.931ms
** * ** * **** total_latency: 2.931,i = 0
^^^^^^^^^^^^^^^^^^^ total_latency:2.931
############### total_latency:0.000发送UDP Ping 1 ....
等待UDP Ping echo ....
延迟[1]:3.066ms
** * ** * **** total_latency: 3.066,i = 1
^^^^^^^^^^^^^^^^^^^ total_latency:3.066
############### total_latency:0.000发送UDP Ping 2 ....
等待UDP Ping echo ....
延迟[2]:3.340ms
** * ** * **** total_latency: 3.340,i = 2
^^^^^^^^^^^^^^^^^^^ total_latency:3.340
static int SendUDPPing(int udpSocket)
{
int i=0, loop = NUM_PING_PROBING;
char szBuf[500];
double diff[NUM_PING_PROBING];
double total_latency=0;
struct timeval start_time[NUM_PING_PROBING], end_time[NUM_PING_PROBING];
int nSelect = 0;
fd_set rfds;
struct timeval timeout;
FD_ZERO(&rfds);
FD_SET(udpSocket, &rfds);
timeout.tv_sec = 0;
timeout.tv_usec = 300000;
while(i < loop)
{
fprintf(stderr, "##################### total_latency:%.3f\n",
total_latency);
fprintf(stderr, "Sending UDP Ping %d....\n", i);
gettimeofday(&start_time[i], NULL);
nRet = send(udpSocket, "ping", strlen("ping"), 0);
if (nRet < 0)
{
fprintf(stderr, "%s UDP Packet send error\n", __func__);
return WBEST_ERR_FAIL;
}
fprintf(stderr, "Waiting for UDP Ping echo....\n");
memset(szBuf, 0, sizeof(szBuf));
nSelect = select(udpSocket+1, &rfds, NULL, NULL, &timeout);
if ( nSelect < 0)
{
fprintf(stderr, "%s: select() failed.\n", __func__);
break;
}
else if (nSelect == 0)
{
fprintf(stderr,
"%s: Receiving UDP PING echo packets timeout (300 ms).\n",
__func__);
break;
}
else
{
nRet = recv(udpSocket, szBuf, sizeof(szBuf), 0);
if (nRet < 0)
{
fprintf(stderr, "%s UDP Packet recv error\n", __func__);
return WBEST_ERR_FAIL;
}
gettimeofday(&end_time[i], NULL);
//fprintf(stderr, "start %lds %ldus, end %lds %ldus\n",
start_time[i].tv_sec, start_time[i].tv_usec,
end_time[i].tv_sec, end_time[i].tv_usec);
if (end_time[i].tv_usec < start_time[i].tv_usec)
{
end_time[i].tv_sec -= 1;
end_time[i].tv_usec += 1000000;
}
diff[i] = ( (double)(end_time[i].tv_sec - start_time[i].tv_sec)
*(double)1000)
+ ((double)(end_time[i].tv_usec
- start_time[i].tv_usec)
/ (double)1000);
total_latency = total_latency + diff[i];
fprintf(stderr, "Latency[%d]: %.3fms\n", i, diff[i]);
fprintf(stderr, "******************** total_latency:%.3f, i=%d\n",
total_latency, i);
i++;
}
fprintf(stderr, "^^^^^^^^^^^^^^^^^^^ total_latency:%.3f\n",
total_latency);
}
fprintf(stderr, "Done\n");
}