Introduction to programming with Sun/ONC RPC: step 5
Step 5. Making the client functional
All we need now to get our program to work is to get the two
numbers from the command line instead of using hard-coded
values. In add_client.c we'll change the main
function to accept three parameters: the server name, the
first number, and the second number. The numbers will be
parsed into integers and passed to add_prog_1.
Our main function used to look like:
main(int argc, char *argv[])
{
char *host;
if (argc < 2) {
printf("usage: %s server_host\n", argv[0]);
exit(1);
}
host = argv[1];
add_prog_1(host);
}
It now looks like:
int
main(int argc, char *argv[])
{
char *host;
int a, b;
if (argc != 4) {
printf ("usage: %s server_host num1 num2\n", argv[0]);
exit(1);
}
host = argv[1];
if ((a = atoi(argv[2])) == 0 && *argv[2] != '0') {
fprintf(stderr, "invalid value: %s\n", argv[2]);
exit(1);
}
if ((b = atoi(argv[3])) == 0 && *argv[3] != '0') {
fprintf(stderr, "invalid value: %s\n", argv[3]);
exit(1);
}
add_prog_1(host, a, b);
}
We change add_prog_1 to accept two additional parameters:
void
add_prog_1(char *host, int a, int b)
and set the parameters for the call to the remote procedure with:
add_1_arg.a = a;
add_1_arg.b = b;
result_1 = add_1(&add_1_arg, clnt);
Before compiling, add a #include <stdio.h> at the start
of the file to define stderr, the file descriptor for the
standard error output used by stdio functions (such as
printf).
The complete client looks like:
#include "add.h"
#include <stdio.h>
void
add_prog_1( char* host, int a, int b )
{
CLIENT *clnt;
int *result_1;
intpair add_1_arg;
clnt = clnt_create(host, ADD_PROG, ADD_VERS, "udp");
if (clnt == NULL) {
clnt_pcreateerror(host);
exit(1);
}
add_1_arg.a = a;
add_1_arg.b = b;
result_1 = add_1(&add_1_arg, clnt);
if (result_1 == NULL) {
clnt_perror(clnt, "call failed:");
}
else
print("return is %d\n", *result_1);
clnt_destroy( clnt );
}
int
main(int argc, char *argv[])
{
char *host;
int a, b;
if (argc != 4) {
printf ("usage: %s server_host num1 num2\n", argv[0]);
exit(1);
}
host = argv[1];
if ((a = atoi(argv[2])) == 0 && *argv[2] != '0') {
fprintf(stderr, "invalid value: %s\n", argv[2]);
exit(1);
}
if ((b = atoi(argv[3])) == 0 && *argv[3] != '0') {
fprintf(stderr, "invalid value: %s\n", argv[3]);
exit(1);
}
add_prog_1(host, a, b);
}
Compile (make) again, run the server, and run the client. For example:
./add_client localhost 5 7
should yield:
result = 12
The program now fully works!