项目中需要用到时间同步,直接使用开源项目ntp中的ntpdate作为客户端来同步时间。
但是又不想直接使用ntpdate这个命令,而是以动态库的形式使用。
1 生成ntpdate.so
在编译ntpdate可执行程序时,可以看到ntpdate依赖libntp.a, version.o, ntpdate.o。
所以ntpdate.so需要由libntp.a, version.o, ntpdate.o生成。
1.1 Makefile
so:
gcc -shared -o ntpdate.so ntpdate.o version.o -L. -lntp -lrt
2 ntpdate.so使用demo
2.1 demo.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv)
{
void *handle;
void (*callfun)();
char *error;
handle = dlopen("./ntpdate.so", RTLD_LAZY);
if(!handle)
{
printf("[%s:%d] %s \n", __func__, __LINE__, dlerror());
exit(1);
}
callfun=dlsym(handle,"ntpdatemain");
if((error=dlerror())!=NULL)
{
printf("[%s:%d] %s \n",__func__, __LINE__, error);
exit(1);
}
callfun(argc, argv);
dlclose(handle);
return 0;
}
2.2 Makefile
main:
gcc -o demo main.c -ldl
3 运行结果
[root@localhost testntp]# date
2013年 11月 20日 星期三 21:50:48 CST
[root@localhost testntp]# date 11190000
2013年 11月 19日 星期二 00:00:00 CST
[root@localhost testntp]# date
2013年 11月 19日 星期二 00:00:02 CST
[root@localhost testntp]# ./demo 202.120.2.101
20 Nov 21:51:14 demo[16355]: step time server 202.120.2.101 offset 165059.783498 sec
[root@localhost testntp]# date
2013年 11月 20日 星期三 21:51:22 CST
[root@localhost testntp]#