Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

656 Advanced IPC Chapter 17


Now let’s look at the open server.It is the programopendthat is executed by the
client in Figure17.19. First, we have theopend.hheader (Figure17.20), which includes
the standardheaders and declares the global variables and function prototypes.
#include "apue.h"
#include <errno.h>

#define CL_OPEN "open" /* client’s request for server */

extern char errmsg[]; /* error message string to return to client */
extern int oflag; /* open() flag: O_xxx ... */
extern char *pathname; /* of file to open() for client */

int cli_args(int, char **);
void handle_request(char *, int, int);

Figure 17.20 Theopend.hheader,version 1

Themainfunction (Figure17.21) reads the requests from the client on the fd-pipe
(its standardinput) and calls the functionhandle_request.
#include "opend.h"

char errmsg[MAXLINE];
int oflag;
char *pathname;

int
main(void)
{
int nread;
char buf[MAXLINE];

for ( ; ; ) { /* read arg buffer from client, process request */
if ((nread = read(STDIN_FILENO, buf, MAXLINE)) < 0)
err_sys("read error on stream pipe");
else if (nread == 0)
break; /* client has closed the stream pipe */
handle_request(buf, nread, STDOUT_FILENO);
}
exit(0);
}

Figure 17.21The servermainfunction, version 1

The functionhandle_requestin Figure17.22 does all the work. It calls the
function buf_args to break up the client’s request into a standard argv-style
argument list and calls the functioncli_argsto process the client’s arguments. If all
is OK,openis called to open the file, and thensend_fdsends the descriptor back to
the client across the fd-pipe (its standardoutput). If an error is encountered,send_err
is called to send back an error message, using the client–server protocol that we
described earlier.
Free download pdf