Open System Services Programmer's Guide

Example 27 Dynamic Echo Server Program
/* dserver.c
*
* Simple OSS server example using OSS APIs for communication
* between requester and server.
*
* dserver is a dynamic echo server. A dserver process is launched
* for each requester. dserver reads stdin and echoes on stdout.
* dserver exits when idle for 60 seconds.
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
/* Guardian APIs */
#include <cextdecs.h(PROCESSHANDLE_GETMINE_, PROCESSHANDLE_DECOMPOSE_)>
short cpu, phandle[10]; /* our cpu and process handle */
int bytesread, readycount; /* ready fd count, recv byte count */
struct timeval timeval; /* timeout structure for select() call */
fd_set fdset; /* set of fds for select() call */
#define IDLE_PERIOD 60 /* 60 seconds */
#define BUFF_LEN 1024 /* buffer size */
char msg_buff[BUFF_LEN+1]; /* single buffer is enough */
int main(int argc, char **argv)
{
/* get process handle and cpu number */
PROCESSHANDLE_GETMINE_(phandle);
PROCESSHANDLE_DECOMPOSE_(phandle, &cpu);
/* print startup message */
fprintf(stderr, "dserver [cpu %d] - starting\n", cpu);
FD_ZERO(&fdset);
/* loop until error or timeout or input closed */
while (1)
{
/* initialize timeout and bitmask for select() call */
timeval.tv_sec = IDLE_PERIOD;
timeval.tv_usec = 0;
FD_SET(STDIN_FILENO, &fdset);
readycount = select(STDIN_FILENO+1, &fdset, NULL, NULL, &timeval);
/* if timeout then exit */
if (readycount == 0)
{
fprintf(stderr, "dserver [cpu %d] - stopping [timeout]\n", cpu);
exit(0);
}
/* fd ready so read data */
if ((bytesread = read(STDIN_FILENO, msg_buff, BUFF_LEN)) < 0)
{
fprintf(stderr, "dserver [cpu %d] - "
"read(fd %d) failed [errno %d]\n",
110 Managing Processes