.\" Must use -- tbl -- for this one
.\" @(#)rpcgen.ms 2.2 88/08/04 4.0 RPCSRC
.\" prevent excess underlining in nroff
.OH '\fBrpcgen\fP Programming Guide''Page %'
.EH 'Page %''\fBrpcgen\fP Programming Guide'
\&\fBrpcgen\fP Programming Guide
\&The \fBrpcgen\fP Protocol Compiler
.IX rpcgen "" \fIrpcgen\fP "" PAGE MAJOR
.IX RPC "" "" \fIrpcgen\fP
The details of programming applications to use Remote Procedure Calls
can be overwhelming. Perhaps most daunting is the writing of the XDR
routines necessary to convert procedure arguments and results into
their network format and vice-versa.
exists to help programmers write RPC applications simply and directly.
does most of the dirty work, allowing programmers to debug
the main features of their application, instead of requiring them to
spend most of their time debugging their network interface code.
is a compiler. It accepts a remote program interface definition written
in a language, called RPC Language, which is similar to C. It produces a C
language output which includes stub versions of the client routines, a
server skeleton, XDR filter routines for both parameters and results, and a
header file that contains common definitions. The client stubs interface
with the RPC library and effectively hide the network from their callers.
The server stub similarly hides the network from the server procedures that
are to be invoked by remote clients.
output files can be compiled and linked in the usual way. The developer
writes server procedures\(emin any language that observes Sun calling
conventions\(emand links them with the server skeleton produced by
to get an executable server program. To use a remote program, a programmer
writes an ordinary main program that makes local procedure calls to the
Linking this program with
stubs creates an executable program. (At present the main program must be
options can be used to suppress stub generation and to specify the transport
to be used by the server stub.
that would otherwise be spent coding and debugging low-level routines.
do this at a small cost in efficiency
and flexibility. However, many compilers allow escape hatches for
programmers to mix low-level code with high-level code.
is no exception. In speed-critical applications, hand-written routines
output without any difficulty. Also, one may proceed by using
output as a starting point, and then rewriting it as necessary.
(If you need a discussion of RPC programming without
.I "Remote Procedure Call Programming Guide)\.
\&Converting Local Procedures into Remote Procedures
.IX rpcgen "local procedures" \fIrpcgen\fP
.IX rpcgen "remote procedures" \fIrpcgen\fP
Assume an application that runs on a single machine, one which we want
to convert to run over the network. Here we will demonstrate such a
conversion by way of a simple example\(ema program that prints a
* printmsg.c: print a message on the console
fprintf(stderr, "usage: %s <message>\en", argv[0]);
if (!printmessage(message)) {
fprintf(stderr, "%s: couldn't print your message\en",
printf("Message Delivered!\en");
* Print a message to the console.
* Return a boolean indicating whether the message was actually printed.
f = fopen("/dev/console", "w");
fprintf(f, "%s\en", msg);
example% \fBcc printmsg.c -o printmsg\fP
example% \fBprintmsg "Hello, there."\fP
was turned into a remote procedure,
then it could be called from anywhere in the network.
Ideally, one would just like to stick a keyword like
procedure to turn it into a remote procedure. Unfortunately,
we have to live within the constraints of the C language, since
it existed long before RPC did. But even without language
support, it's not very difficult to make a procedure remote.
In general, it's necessary to figure out what the types are for
all procedure inputs and outputs. In this case, we have a
which takes a string as input, and returns an integer
as output. Knowing this, we can write a protocol specification in RPC
language that describes the remote version of
* msg.x: Remote message printing protocol
int PRINTMESSAGE(string) = 1;
Remote procedures are part of remote programs, so we actually declared
an entire remote program here which contains the single procedure
This procedure was declared to be in version 1 of the
remote program. No null procedure (procedure 0) is necessary because
generates it automatically.
Notice that everything is declared with all capital letters. This is
not required, but is a good convention to follow.
Notice also that the argument type is \*Qstring\*U and not \*Qchar *\*U. This
is because a \*Qchar *\*U in C is ambiguous. Programmers usually intend it
to mean a null-terminated string of characters, but it could also
represent a pointer to a single character or a pointer to an array of
characters. In RPC language, a null-terminated string is
unambiguously called a \*Qstring\*U.
There are just two more things to write. First, there is the remote
procedure itself. Here's the definition of a remote procedure
procedure we declared above:
* msg_proc.c: implementation of the remote procedure "printmessage"
#include <rpc/rpc.h> /* \fIalways needed\fP */
#include "msg.h" /* \fIneed this too: msg.h will be generated by rpcgen\fP */
* Remote verson of "printmessage"
static int result; /* \fImust be static!\fP */
f = fopen("/dev/console", "w");
fprintf(f, "%s\en", *msg);
Notice here that the declaration of the remote procedure
differs from that of the local procedure
It takes a pointer to a string instead of a string itself. This
is true of all remote procedures: they always take pointers to their
arguments rather than the arguments themselves.
It returns a pointer to an integer instead of an integer itself. This is
also generally true of remote procedures: they always return a pointer
It has an \*Q_1\*U appended to its name. In general, all remote
are named by the following rule: the name in the program definition
lower-case letters, an underbar (\*Q_\*U) is appended to it, and
finally the version number (here 1) is appended.
The last thing to do is declare the main client program that will call
the remote procedure. Here it is:
* rprintmsg.c: remote version of "printmsg.c"
#include <rpc/rpc.h> /* \fIalways needed\fP */
#include "msg.h" /* \fIneed this too: msg.h will be generated by rpcgen\fP */
fprintf(stderr, "usage: %s host message\en", argv[0]);
* Save values of command line arguments
* Create client "handle" used for calling \fIMESSAGEPROG\fP on the
* server designated on the command line. We tell the RPC package
* to use the "tcp" protocol when contacting the server.
cl = clnt_create(server, MESSAGEPROG, MESSAGEVERS, "tcp");
* Couldn't establish connection with server.
* Print error message and die.
clnt_pcreateerror(server);
* Call the remote procedure "printmessage" on the server
result = printmessage_1(&message, cl);
* An error occurred while calling the server.
* Print error message and die.
* Okay, we successfully called the remote procedure.
* Server was unable to print our message.
* Print error message and die.
fprintf(stderr, "%s: %s couldn't print your message\en",
* The message got printed on the server's console
printf("Message delivered to %s!\en", server);
There are two things to note here:
.IX "client handle, used by rpcgen" "" "client handle, used by \fIrpcgen\fP"
First a client \*Qhandle\*U is created using the RPC library routine
This client handle will be passed to the stub routines
which call the remote procedure.
is called exactly the same way as it is declared in
except for the inserted client handle as the first argument.
Here's how to put all of the pieces together:
example% \fBrpcgen msg.x\fP
example% \fBcc rprintmsg.c msg_clnt.c -o rprintmsg\fP
example% \fBcc msg_proc.c msg_svc.c -o msg_server\fP
Two programs were compiled here: the client program
Before doing this though,
was used to fill in the missing pieces.
It created a header file called
for use in the other modules.
It created client \*Qstub\*U routines in the
file. In this case there is only one, the
that was referred to from the
client program. The name of the output file for
client stub routines is always formed in this way: if the name of the
the client stubs output file is called
It created the server program which calls
This server program is named
The rule for naming the server output file is similar to the
previous one: for an input file called
the output server file is named
Now we're ready to have some fun. First, copy the server to a
remote machine and run it. For this example, the
machine is called \*Qmoon\*U. Server processes are run in the
background, because they never exit.
Then on our local machine (\*Qsun\*U) we can print a message on \*Qmoon\*Us
sun% \fBprintmsg moon "Hello, moon."\fP
The message will get printed to \*Qmoon\*Us console. You can print a
message on anybody's console (including your own) with this program if
you are able to copy the server to their machine and run it.
\&Generating XDR Routines
.IX RPC "generating XDR routines"
The previous example only demonstrated the automatic generation of
client and server RPC code.
may also be used to generate XDR routines, that is, the routines
necessary to convert local data
structures into network format and vice-versa. This example presents
a complete RPC service\(ema remote directory listing service, which uses
not only to generate stub routines, but also to generate the XDR
routines. Here is the protocol description file:
* dir.x: Remote directory listing protocol
const MAXNAMELEN = 255; /* \fImaximum length of a directory entry\fP */
typedef string nametype<MAXNAMELEN>; /* \fIa directory entry\fP */
typedef struct namenode *namelist; /* \fIa link in the listing\fP */
* A node in the directory listing
nametype name; /* \fIname of directory entry\fP */
namelist next; /* \fInext entry\fP */
* The result of a READDIR operation.
union readdir_res switch (int errno) {
namelist list; /* \fIno error: return directory listing\fP */
void; /* \fIerror occurred: nothing else to return\fP */
* The directory program definition
in the example above) can be defined using
the \*Qstruct\*U, \*Qunion\*U and \*Qenum\*U keywords, but those keywords
should not be used in subsequent declarations of variables of those types.
For example, if you define a union \*Qfoo\*U, you should declare using
only \*Qfoo\*U and not \*Qunion foo\*U. In fact,
RPC unions into C structures and it is an error to declare them using the
creates four output files. Three are the same as before: header file,
client stub routines and server skeleton. The fourth are the XDR routines
necessary for converting the data types we declared into XDR format and
vice-versa. These are output in the file
Here is the implementation of the
* dir_proc.c: remote readdir implementation
static readdir_res res; /* \fImust be static\fP! */
dirp = opendir(*dirname);
xdr_free(xdr_readdir_res, &res);
* Collect directory entries.
* Memory allocated here will be freed by \fIxdr_free\fP
* next time \fIreaddir_1\fP is called
nlp = &res.readdir_res_u.list;
while (d = readdir(dirp)) {
nl = *nlp = (namenode *) malloc(sizeof(namenode));
nl->name = strdup(d->d_name);
Finally, there is the client side program to call the server:
* rls.c: Remote directory listing client
#include <rpc/rpc.h> /* \fIalways need this\fP */
#include "dir.h" /* \fIwill be generated by rpcgen\fI */
fprintf(stderr, "usage: %s host directory\en",
* Remember what our command line arguments refer to
* Create client "handle" used for calling \fIMESSAGEPROG\fP on the
* server designated on the command line. We tell the RPC package
* to use the "tcp" protocol when contacting the server.
cl = clnt_create(server, DIRPROG, DIRVERS, "tcp");
* Couldn't establish connection with server.
* Print error message and die.
clnt_pcreateerror(server);
* Call the remote procedure \fIreaddir\fP on the server
result = readdir_1(&dir, cl);
* An error occurred while calling the server.
* Print error message and die.
* Okay, we successfully called the remote procedure.
if (result->errno != 0) {
* A remote system error occurred.
* Print error message and die.
* Successfully got a directory listing.
for (nl = result->readdir_res_u.list; nl != NULL;
printf("%s\en", nl->name);
Compile everything, and run.
sun% \fBcc rls.c dir_clnt.c dir_xdr.c -o rls\fP
sun% \fBcc dir_svc.c dir_proc.c dir_xdr.c -o dir_svc\fP
moon% \fBrls sun /usr/pub\fP
.IX "debugging with rpcgen" "" "debugging with \fIrpcgen\fP"
The client program and the server procedure can be tested together
as a single program by simply linking them with each other rather
than with the client and server stubs. The procedure calls will be
executed as ordinary local procedure calls and the program can be
debugged with a local debugger such as
When the program is working, the client program can be linked to
the client stub produced by
and the server procedures can be linked to the server stub produced
\fIIf you do this, you may want to comment out calls to RPC library
routines, and have client-side routines call server routines
.IX rpcgen "C-preprocessor" \fIrpcgen\fP
The C-preprocessor is run on all input files before they are
compiled, so all the preprocessor directives are legal within a \*Q.x\*U
file. Four symbols may be defined, depending upon which output file is
getting generated. The symbols are:
RPC_HDR&for header-file output
RPC_XDR&for XDR routine output
RPC_SVC&for server-skeleton output
RPC_CLNT&for client stub output
does a little preprocessing of its own. Any line that
begins with a percent sign is passed directly into the output file,
without any interpretation of the line. Here is a simple example that
demonstrates the preprocessing features.
* time.x: Remote time protocol
unsigned int TIMEGET(void) = 1;
The '%' feature is not generally recommended, as there is no guarantee
that the compiler will stick the output where you intended.
\&\fBrpcgen\fP Programming Notes
.IX rpcgen "other operations" \fIrpcgen\fP
.IX rpcgen "timeout changes" \fIrpcgen\fP
RPC sets a default timeout of 25 seconds for RPC calls when
is used. This timeout may be changed using
Here is a small code fragment to demonstrate use of
cl = clnt_create("somehost", SOMEPROG, SOMEVERS, "tcp");
tv.tv_sec = 60; /* \fIchange timeout to 1 minute\fP */
clnt_control(cl, CLSET_TIMEOUT, &tv);
\&Handling Broadcast on the Server Side
.IX rpcgen "broadcast RPC" \fIrpcgen\fP
When a procedure is known to be called via broadcast RPC,
it is usually wise for the server to not reply unless it can provide
some useful information to the client. This prevents the network
from getting flooded by useless replies.
To prevent the server from replying, a remote procedure can
return NULL as its result, and the server code generated by
will detect this and not send out a reply.
Here is an example of a procedure that replies only if it
thinks it is an NFS server:
char notnull; /* \fIjust here so we can use its address\fP */
if (access("/etc/exports", F_OK) < 0) {
return (NULL); /* \fIprevent RPC from replying\fP */
* return non-null pointer so RPC will send out a reply
return ((void *)¬null);
Note that if procedure returns type \*Qvoid *\*U, they must return a non-NULL
pointer if they want RPC to reply for them.
\&Other Information Passed to Server Procedures
Server procedures will often want to know more about an RPC call
than just its arguments. For example, getting authentication information
is important to procedures that want to implement some level of security.
This extra information is actually supplied to the server procedure as a
second argument. Here is an example to demonstrate its use. What we've
done here is rewrite the previous
procedure to only allow root users to print a message to the console.
static in result; /* \fIMust be static\fP */
struct suthunix_parms *aup;
aup = (struct authunix_parms *)rq->rq_clntcred;
.IX rpcgen "RPC Language" \fIrpcgen\fP
RPC language is an extension of XDR language. The sole extension is
type. For a complete description of the XDR language syntax, see the
.I "External Data Representation Standard: Protocol Specification"
chapter. For a description of the RPC extensions to the XDR language,
.I "Remote Procedure Calls: Protocol Specification"
However, XDR language is so close to C that if you know C, you know most
of it already. We describe here the syntax of the RPC language,
showing a few examples along the way. We also show how the various
RPC and XDR type definitions get compiled into C type definitions in
.IX rpcgen definitions \fIrpcgen\fP
An RPC language file consists of a series of definitions.
definition ";" definition-list
It recognizes five types of definitions.
.IX rpcgen structures \fIrpcgen\fP
An XDR struct is declared almost exactly like its C counterpart. It
looks like the following:
"struct" struct-ident "{"
declaration ";" declaration-list
As an example, here is an XDR structure to a two-dimensional
coordinate, and the C structure that it gets compiled into in the
struct coord { struct coord {
typedef struct coord coord;
The output is identical to the input, except for the added
at the end of the output. This allows one to use \*Qcoord\*U instead of
\*Qstruct coord\*U when declaring items.
.IX rpcgen unions \fIrpcgen\fP
XDR unions are discriminated unions, and look quite different from C
unions. They are more analogous to Pascal variant records than they
"union" union-ident "switch" "(" declaration ")" "{"
"case" value ":" declaration ";"
"default" ":" declaration ";"
"case" value ":" declaration ";" case-list
Here is an example of a type that might be returned as the result of a
\*Qread data\*U operation. If there is no error, return a block of data.
Otherwise, don't return anything.
union read_result switch (int errno) {
It gets compiled into the following:
typedef struct read_result read_result;
Notice that the union component of the output struct has the name as
the type name, except for the trailing \*Q_u\*U.
.IX rpcgen enumerations \fIrpcgen\fP
XDR enumerations have the same syntax as C enumerations.
enum-value "," enum-value-list
enum-value-ident "=" value
Here is a short example of an XDR enum, and the C enum that it gets
enum colortype { enum colortype {
GREEN = 1, --> GREEN = 1,
typedef enum colortype colortype;
.IX rpcgen typedef \fIrpcgen\fP
XDR typedefs have the same syntax as C typedefs.
Here is an example that defines a
file name strings that have a maximum length of 255 characters.
typedef string fname_type<255>; --> typedef char *fname_type;
.IX rpcgen constants \fIrpcgen\fP
XDR constants symbolic constants that may be used wherever a
integer constant is used, for example, in array size specifications.
"const" const-ident "=" integer
For example, the following defines a constant
const DOZEN = 12; --> #define DOZEN 12
.IX rpcgen programs \fIrpcgen\fP
RPC programs are declared using the following syntax:
"program" program-ident "{"
"version" version-ident "{"
procedure ";" procedure-list
type-ident procedure-ident "(" type-ident ")" "=" value
For example, here is the time protocol, revisited:
* time.x: Get or set the time. Time is represented as number of seconds
* since 0:00, January 1, 1970.
unsigned int TIMEGET(void) = 1;
void TIMESET(unsigned) = 2;
This file compiles into #defines in the output header file:
.IX rpcgen declarations \fIrpcgen\fP
In XDR, there are only four kinds of declarations.
variable-array-declaration
\fB1) Simple declarations\fP are just like simple C declarations.
type-ident variable-ident
colortype color; --> colortype color;
\fB2) Fixed-length Array Declarations\fP are just like C array declarations:
type-ident variable-ident "[" value "]"
colortype palette[8]; --> colortype palette[8];
\fB3) Variable-Length Array Declarations\fP have no explicit syntax
in C, so XDR invents its own using angle-brackets.
variable-array-declaration:
type-ident variable-ident "<" value ">"
type-ident variable-ident "<" ">"
The maximum size is specified between the angle brackets. The size may
be omitted, indicating that the array may be of any size.
int heights<12>; /* \fIat most 12 items\fP */
int widths<>; /* \fIany number of items\fP */
Since variable-length arrays have no explicit syntax in C, these
declarations are actually compiled into \*Qstruct\*Us. For example, the
\*Qheights\*U declaration gets compiled into the following struct:
u_int heights_len; /* \fI# of items in array\fP */
int *heights_val; /* \fIpointer to array\fP */
Note that the number of items in the array is stored in the \*Q_len\*U
component and the pointer to the array is stored in the \*Q_val\*U
component. The first part of each of these component's names is the
same as the name of the declared XDR variable.
\fB4) Pointer Declarations\fP are made in
XDR exactly as they are in C. You can't
really send pointers over the network, but you can use XDR pointers
for sending recursive data types such as lists and trees. The type is
actually called \*Qoptional-data\*U, not \*Qpointer\*U, in XDR language.
type-ident "*" variable-ident
listitem *next; --> listitem *next;
.IX rpcgen "special cases" \fIrpcgen\fP
There are a few exceptions to the rules described above.
C has no built-in boolean type. However, the RPC library does a
in XDR language are compiled into
in the output header file.
bool married; --> bool_t married;
C has no built-in string type, but instead uses the null-terminated
\*Qchar *\*U convention. In XDR language, strings are declared using the
\*Qstring\*U keyword, and compiled into \*Qchar *\*Us in the output header
file. The maximum size contained in the angle brackets specifies the
maximum number of characters allowed in the strings (not counting the
character). The maximum size may be left off, indicating a string
string name<32>; --> char *name;
string longname<>; --> char *longname;
Opaque data is used in RPC and XDR to describe untyped data, that is,
just sequences of arbitrary bytes. It may be declared either as a
fixed or variable length array.
opaque diskblock[512]; --> char diskblock[512];
opaque filedata<1024>; --> struct {
In a void declaration, the variable is not named. The declaration is
just \*Qvoid\*U and nothing else. Void declarations can only occur in two
places: union definitions and program definitions (as the argument or
result of a remote procedure).