Sun RPC 编程简介( 三 )


#include
#include /* always needed */
#include "time.h" /* time.h will be generated by rpcgen */
#include
/* Remote version of "printime" */
char ** printime_1(char **msg,struct svc_req *req)

{
static char * result; /* must be static! */
static char tmp_char[100];
time_t rawtime;

FILE *f;

f = fopen("/tmp/rpc_result", "a ");
if (f == (FILE *)NULL) {
strcpy(tmp_char,"Error");
result = tmp_char
return (&result);
}
fprintf(f, "%sn", *msg); //used for debugging
fclose(f);
time(&rawtime);
sprintf(tmp_char,"Current time is :%s",ctime(&rawtime));
result =tmp_char;
return (&result);
}
rtime.c源代码
/*
* rtime.c: remote version
* of "printime.c"
*/

#include
#include "time.h" /* time.h generated by rpcgen */

main(int argc, char **argv)

{
CLIENT *clnt;
char *result;
char *server;
char *message;


if (argc != 3) {
fprintf(stderr, "usage: %s host messagen", argv[0]);
exit(1);
}

server = argv[1];
message = argv[2];

/*
* Create client "handle" used for
* calling TIMEPROG on the server
* designated on the command line.
*/

clnt = clnt_create(server, TIMEPROG, PRINTIMEVERS, "visible");

if (clnt == (CLIENT *)NULL) {
/*
* Couldn"t establish connection
* with server.
* Print error message and die.
*/

clnt_pcreateerror(server);
exit(1);
}

/*

* Call the remote procedure
* "printime" on the server
*/

result =*printime_1(&message,clnt);
if (result== (char *)NULL) {
/*
* An error occurred while calling
* the server.
* Print error message and die.
*/

clnt_perror(clnt, server);
exit(1);
}

/* Okay, we successfully called
* the remote procedure.
*/

if (strcmp(result,"Error") == 0) {

/*
* Server was unable to print
* the time.
* Print error message and die.
*/

fprintf(stderr, "%s: could not get the timen",argv[0]);
exit(1);
}
printf("From the Time Server ...%sn",result);
clnt_destroy( clnt );
exit(0);
}
有了以上的三段代码后,就可用rpcgen 编译工具进行RPC协议编译,命令如下:
$rpcgen time.x
rpcgen 会自动生成time.h、time_svc.c、time_clnt.c
再用系统提供的gcc进行C的编译,命令如下:
$gcc rtime.c time_clnt.c -o rtime -lnsl //客户端编译
$gcc time_proc.c time_svc.c -o time_server -lnsl //服务器端编译
编译成功后即可在Server端运行time_server,立即将该服务绑定在rpc服务端口上提供
服务 。在客户端运行./rdate hostname msg (msg 是一字符串,笔者用来测试时建立的),
立即会返回hostname 端的时间 。
由于,在Sun Solaris 中无法获取远端Server 上时钟信息的功能(不改变本
地Server时钟),笔者曾将此程序应用于计费服务器同时钟服务器同步监测的网管
系统中,运行稳定,获得了较好的效果 。应该说RPC的应用是十分广泛的,特别是
在分布式计算领域中尤为显得重要 。当然,笔者也是刚接触RPC,还有很多地方了
解的不够深刻,望广大读者多指教 。



参考文献:
《SUN Solaris8 ONCDev》

推荐阅读