【发布时间】:2010-01-27 13:42:04
【问题描述】:
我需要一些关于我为 Nagios 编写的插件的建议和帮助。
我正在用 C 语言编写插件,但在尝试让这个插件工作时,除了少量的经验外,没有以前的语言经验。
基本上我要做的是以下。
读取由我编写的应用程序在远程 PC 上生成的文本文件,该程序向文件中写入的字符不超过 5 个,前 4 个字符是 24 小时格式的时间。例如22:30 > 晚上 10:30
然后它需要将这 4 个字符转换成一个时间,并将其与当前系统时间进行比较(如果有 5 分钟的差异,则它会向 nagios 生成一个回复以标记警告)。
我尝试了很多不同的方法,我的第一次尝试是将字符转换为整数,然后将时间转换为整数并比较差异..这样做失败了。
我的第二次尝试是生成两个时间结构,一个是当前时间,另一个是我的“自制”时间,然后比较它们,但这也不起作用。
这是我的代码,无论我尝试什么,文件中的日期始终与当前系统时间相同,我知道它与必须在顶部设置时间有关。
t_of_file = time(NULL);
time_from_file = localtime(&t_of_file);
但如果我不这样做,我会遇到分段错误。
这是代码。
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define COPYMODE 0644
int main(int argc, char *argv[])
{
struct tm *time_from_file;
struct tm *the_system_time;
time_t t_of_file;
time_t t_of_sys;
t_of_sys = time(NULL);
the_system_time = localtime(&t_of_sys);
t_of_file = time(NULL);
time_from_file = localtime(&t_of_file);
time_from_file->tm_year = the_system_time->tm_year;
time_from_file->tm_mon = the_system_time->tm_mon;
time_from_file->tm_mday = the_system_time->tm_mday;
time_from_file->tm_hour = 10; //should be read in from file
time_from_file->tm_min = 30; //should be read in from file
time_from_file->tm_sec = the_system_time->tm_sec;
time_from_file->tm_isdst = the_system_time->tm_isdst;
t_of_file = mktime(time_from_file);
printf("%s\n",ctime(&t_of_file));
t_of_sys = mktime(the_system_time);
printf("%s\n",ctime(&t_of_sys));
double difference = difftime(t_of_file, t_of_sys );
printf("%lf\n",(double)t_of_file);
printf("%lf\n",(double)t_of_sys);
if (difference >= 0.0) { //this should be 5 mins, not quite sure what to put here yet
// second is later than first
printf("later\n");
}
else if (difference < 0.0) {
// second is earlier than first
printf("earlier\n");
}
printf("%lf\n", difference);
return 0;//STATE_OK;
}
您能提供的任何帮助将不胜感激。
根据我得到的答案,PACE 的答案是我想做的事情,现在我有一个更简单的代码,它非常适合我想要做的事情并且更容易理解。下面是修改后的代码(顺便说一句,它可以在 Linux 上完美编译)。
#include <stdio.h>
#include <time.h>
int main ()
{
time_t filetime;
time_t presenttime;
struct tm * timeinfo;
time ( &filetime );
time ( &presenttime);
timeinfo = localtime ( &filetime );
timeinfo->tm_hour = 14; //this should be entered from file
timeinfo->tm_min = 15; //this should be entered from file
filetime = mktime ( timeinfo );
printf("my time %s\n",ctime(&filetime));
printf("pc time %s\n",ctime(&presenttime));
double difference = difftime(filetime, presenttime );
printf("%lf\n",(double)filetime);
printf("%lf\n",(double)presenttime);
if (difference > 300.0) {
// second is later than first
printf("later\n");
}
else if (difference < 0.0) {
// second is earlier than first
printf("earlier\n");
}
printf("%lf\n", difference);
return 0;
为帮助的家伙干杯。
【问题讨论】:
标签: c datetime date comparison