Open System Services Programmer's Guide
addr.sin_family = AF_INET; /* internet address family */
addr.sin_addr.s_addr = gethostid(); /* assume server on our host */
/* bind socket to address ... if error then exit(1) */
if (bind_nw(fd, (struct sockaddr *)&addr, sizeof(addr), bind_tag) < 0)
{
printf("bind_nw() call failed [errno %d]\n", errno);
exit(1);
}
AWAITIOX(&fd, , , , FOREVER);
/* start a nowait accept ... if error then exit(1) */
addrlen = sizeof(addr);
if (accept_nw(fd, (struct sockaddr *)&addr, &addrlen, accept_tag) < 0)
{
printf("accept_nw() call failed [errno %d]\n", errno);
exit(1);
}
listenfd = fd;
/* Find a finished nowait operation */
while (1)
{
fd = -1;
AWAITIOX(&fd, (long *) &bufferptr, &bytesread, &tag,
IDLE_PERIOD);
/* if timeout then exit(0) */
if (fd == -1)
{
printf("Server stopping\n");
exit(0);
}
/* if incoming connection, accept connection */
if (fd == listenfd)
{
/* create a new socket ... if error then exit(1) */
if ((newfd = (short) socket_nw(AF_INET, SOCK_STREAM, 0,
NOWAIT, SYNC) ) < 0)
{
printf("socket_nw() call failed [errno %d]\n", errno);
exit(1);
}
AWAITIOX(&newfd, , , , FOREVER); /* should finish quickly */
/* if too many connections then exit(1) */
if (newfd > MAX_FDS)
{
printf("Too many connections\n");
exit(1);
}
msg_buff_ptr[newfd] = malloc(BUFF_LEN+1);
/* accept the connection using the filled in addr
* buffer from the finished accept_nw() call. */
if (accept_nw2(newfd, (struct sockaddr *)&addr, accept_tag) < 0)
{
printf("accept_nw2() call failed [errno %d]\n", errno);
exit(1);
}
AWAITIOX(&newfd, , , , FOREVER); /* should finish quickly */
/* need to post a recv() for AWAITIOX() to complete */
if (recv_nw(newfd, bufferptr, BUFF_LEN, 0, recv_tag) < 0)
{
printf("recv() call failed [errno %d]\n", errno);
exit(1);
}
186 Interprocess Communication