Open System Services Programmer's Guide
Example 105 Threaded Time-of-Day Server Socket
/* Threaded time-of day server socket. */
/* If compiled for TNS/E, specify the ZPUTDLL, */
/* the standard POSIX threads shared run-time library. */
#define _PUT_MODEL_
#define _XOPEN_SOURCE_EXTENDED 1
#include <assert.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
/*
Defines thread-aware functions calls to the threads package:
*/
#include <pthread.h>
/*
Defines a short macro to convert file descriptors to non-blocking
(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;
Threaded Application Programming 433