我已经实现了两个单线程进程A和B,并使用两个消息队列[分别用于发送和接收]。进程A将向B发送一条消息,并在接收队列中等待回复。
我想从进程A向进程B发送时间戳。如果进程B在10秒后接收到该消息,我希望从进程B向进程A发送一个错误字符串。
精度应该是毫秒级别的。
在进程A中,我使用了:
struct timespec msg_dispatch_time;
clock_gettime(CLOCK_REALTIME, &msg_dispatch_time);
:
:
add_timestamp_in_msg(msg, msg_dispatch_time);
:
if (msgsnd(msqid, msg, sizeof(msg), msgflg) == -1)
perror("msgop: msgsnd failed");
在B过程中,
struct timespec msg_dispatch_time;
struct timespec msg_receive_time;
:
clock_gettime(CLOCK_REALTIME, &msg_received_time);
:
if( !(time_diff(msg_received_time, msg_dispatch_time) >= 10 ))
msgsnd(msqid, &sbuf, buf_length, msg_flag)
else
{
/*send the error string.*/
//msgsnd(msgid,)
}
我的问题是,
1)如何在这里编写一个time_diff函数,以毫秒精度进行比较,与10秒进行比较?
if( !(time_diff(msg_received_time, msg_dispatch_time) >= 10 ))
/********Existing time diff code******************/
long int time_diff (struct timeval time1, struct timeval time2)
{
struct timeval diff,
if (time1.tv_usec < time2.tv_usec) {
time1.tv_usec += 1000000;
time1.tv_sec--;
}
diff.tv_usec = time1.tv_usec - time2.tv_usec;
diff.tv_sec = time1.tv_sec - time2.tv_sec;
return diff.tv_sec; //return the diff in second
}
2) clock_gettime在同一系统中的进程间使用是否安全?
enum { NS_PER_SECOND = 1000000000 }; void sub_timespec(struct timespec t1, struct timespec t2, struct timespec *td) { td->tv_nsec = t2.tv_nsec - t1.tv_nsec; td->tv_sec = t2.tv_sec - t1.tv_sec; if (td->tv_sec > 0 && td->tv_nsec < 0) { td->tv_nsec += NS_PER_SECOND; td->tv_sec--; } else if (td->tv_sec < 0 && td->tv_nsec > 0) { td->tv_nsec -= NS_PER_SECOND; td->tv_sec++; } }
- Jonathan Lefflertimeval_subtract()
是针对struct timeval
而不是struct timespec
,是吗?但是这些概念可以应用于其他类型。 - Jonathan Leffler