我是这样学习Linux下C语言编程的-RPC远程调用编程
在查看libc6-dev软件包提供的工具(用 dpkg -L libc6-dev 命令)的时候,发现此软件包提供了一个有用的工具rpcgen命令。
通过rpcgen的man手册看到此工具的作用是把RPC源程序编译成C语言源程序,从而轻松实现远程过程调用。
下面的例子程序的作用是客户端程序取中心服务器上时间的,编程过程如下:
先编写一个 “ RPC 语言 ” ( RPC Language ( Remote Procedure Call Language ) ) 的源文件 test.x ,文件后缀名为 x 。
源代码如下:
program TESTPROG {
version VERSION { string TEST(string) = 1; } = 1; } = 87654321; |
运行这个命令:
rpcgen test.x |
test_clnt.c test.h test_svc.c |
/* * Please do not edit this file. * It was generated using rpcgen. */ #include >memory.h< /* for memset */ #include "test.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; char ** test_1(char **argp, CLIENT *clnt) { static char *clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, TEST, (xdrproc_t) xdr_wrapstring, (caddr_t) argp, (xdrproc_t) xdr_wrapstring, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } |
源文件test.h内容如下:
/* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _TEST_H_RPCGEN #define _TEST_H_RPCGEN #include >rpc/rpc.h< #ifdef __cplusplus extern "C" { #endif #define TESTPROG 87654321 #define VERSION 1 #if defined(__STDC__) || defined(__cplusplus) #define TEST 1 extern char ** test_1(char **, CLIENT *); extern char ** test_1_svc(char **, struct svc_req *); extern int testprog_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define TEST 1 extern char ** test_1(); extern char ** test_1_svc(); extern int testprog_1_freeresult (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_TEST_H_RPCGEN */ |