如何在ansi -c sun-rpc中将结构从服务器正确发送到客户端?
在我的 test.x IDL文件中,我定义了一个带有字符串和int的结构集群 和一个类型集群,它是一个可变长度的集群元素数组:
struct cluster {
string name<255>;
int debuglevel;
};
typedef cluster clusters<32>;
然后我改变了rpcgen生成的存根,如
test_server.c
clusters *
test_1_svc(void *argp, struct svc_req *rqstp)
{
static clusters result;
cluster cl1, cl2;
cl1.name="cl1";
cl1.debuglevel="1";
cl2.name="cl2";
cl2.debuglevel="2";
cluster clist[2];
clist[0]=cl1;
clist[1]=cl2;
result.clusters_len = 2;
result.clusters_val = &clist;
/*
* insert server code here
*/
return(&result);
}
和 test_client.c
test_prog_1( char* host )
{
CLIENT *clnt;
clusters *result_1;
char* test_1_arg;
clnt = clnt_create(host, test_PROG, test_VERS, "udp");
if (clnt == NULL) {
clnt_pcreateerror(host);
exit(1);
}
result_1 = test_1((void*)&test_1_arg, clnt);
if (result_1 == NULL) {
clusters* rec_cls = malloc(2*sizeof(struct cluster));
if(xdr_clusters(&result_1, rec_cls)){
printf("got xdr_clusters");
}
clnt_perror(clnt, "call failed:");
}
clnt_destroy( clnt );
}
两者都编译,但是服务器经常在客户端运行一个或两个请求之后发生段错误,而在客户端上,xdr_clusters函数永远不会返回true。这似乎是某种内存管理不善,我也不确定我是否正确处理了服务器端的序列化。
我只是将result.clusters_len和result.clusters_val填充为适当的值,就像它们在 test.h 中定义的那样(由rpcgen提供):
typedef struct {
u_int clusters_len;
cluster *clusters_val;
} clusters;
我是否必须在服务器端使用xdr_clusters才能正确序列化结果?
谢谢
答案 0 :(得分:0)
<强> test_server.c 强>
test_1_svc(void *argp, struct svc_req *rqstp){
static clusters result;
cluster cl1, cl2;
cl1.name="cl1";
cl1.debuglevel=1;
cl2.name="cl2";
cl2.debuglevel=2;
result.clusters_len = 2;
result.clusters_val = malloc(2*sizeof(struct cluster));
result.clusters_val[0]=cl1;
result.clusters_val[1]=cl2;
return(&result);
}
<强> test_client.c 强>
test_prog_1( char* host )
{
CLIENT *clnt;
clusters *result_1;
char* test_1_arg;
clnt = clnt_create(host, test_PROG, test_VERS, "udp");
if (clnt == NULL) {
clnt_pcreateerror(host);
exit(1);
}
result_1 = test_1((void*)&test_1_arg, clnt);
if (result_1 == NULL) {
clnt_perror(clnt, "call failed:");
}else{
printf("I got %d cluster structs in an array\n",result_1->clusters_len);
int j;
for(j=0;j<result_1->clusters_len;j++){
printf("cluster #%d: %s@runlevel %d\n",j,result_1->clusters_val[j].name,result_1->clusters_val[j].debuglevel);
}
}
clnt_destroy( clnt );
}
因此,我们在客户端打印上获得了一些不错的值 当然,在服务器端不再出现段错误:
lars$ ./test_client localhost
I got 2 cluster structs in an array
cluster #0: cl1@runlevel 1
cluster #1: cl2@runlevel 2