Open System Services Programmer's Guide

Example 67 Threaded Time-of-Day Server Socket
/* Threaded time-of day server socket. */
/* If compiled for TNS/R, specify the ZSPTSRL compilation option. */
/* If compiled for TNS/E, specify the ZSPTDLL, the standard POSIX threads */
/* shared run-time library. */
#include <assert.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
/*
Defines thread-aware functions calls to the threads package:
*/
#define SPT_THREAD_AWARE
#include <spthread.h>
/*
Defines a short macro to convert file descriptors to non-blocking (T1248s
thread-aware functions are thread-aware only if the file descriptor is non-
blocking):
*/
#define fd_make_nonblock(fd) \
assert(fcntl(fd,F_SETFL,fcntl(fd,F_GETFL)|O_NONBLOCK) != -1)
/*
Defines the port the server will run on:
*/
#define SERVER_PORT 3000
/*
Shows the worker thread that is created after each accept:
*/
void *worker_thread(void* sock_fd)
{
char buffer[1024];
time_t now;
time(&now);
strcpy(buffer, ctime(&now));
send(*(int *)sock_fd, &buffer, strlen(buffer), 0);
close(*(int *)sock_fd);
return NULL;
}
int main(int argc, char *argv[])
{
int inet_addr_port = SERVER_PORT;
int sock=-1,accept_fd=-1;
size_t size;
struct sockaddr_in servaddr, accept_addr;
/*
Defines one pthread_t per request we intend to handle:
*/
pthread_t my_thread;
pthread_attr_t my_attr;
/*
Turns on concurrency:
*/
336 Using the Standard POSIX Threads Library