You are on page 1of 14

Table of Contents

1 A Very Brief Introduction to Computer Networks


Network Programming
2. Programming with sockets 2 IP Addressing and Name Resolution

Guillaume Pierre 3 UDP Sockets

Vrije Universiteit
4 TCP Sockets
Spring 2008
http://www.cs.vu.nl/~gpierre/courses/np/ 5 I/O Multiplexing

6 Server Structures

Network Programming 2. Programming with sockets 1 / 54 Network Programming 2. Programming with sockets 2 / 54

Reader Table of Contents

1 A Very Brief Introduction to Computer Networks


Mandatory:
I Thinking in Java, Bruce Eckel, 2nd edition, pages 903–926. Freely 2 IP Addressing and Name Resolution
available from http://www.cs.vu.nl/~gpierre/courses/np/
Recommended (but not mandatory) if you want to learn more: 3 UDP Sockets
I Unix Network Programming, Richard Stevens, Prentice Hall editor, 2nd
edition, 1st volume.
4 TCP Sockets
Download the assignment from
http://www.cs.vu.nl/~gpierre/courses/np/
5 I/O Multiplexing
Deadline: 18 March 2008

6 Server Structures

Network Programming 2. Programming with sockets 3 / 54 Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 4 / 54
Introduction Two Different Kinds of Networks

Circuit switching
IOne electrical circuit is assigned to each communication
There is one way computers can communicate together IExample: the phone network
⊕ Guaranteed constant quality of service
I By sending network messages to each other
Waste of resources (periods of silence), fault tolerance
I All other kinds of communications are built from messages
There is one way programs can send/receive network messages Packet switching
I Messages are split into packets, which are transmitted independently
I Through sockets
F Packets can take different routes
I All other communication paradigms are built from sockets F Network infrastructures are shared among users
I Example: the Internet, most computer networks

⊕ Good resource usage, fault tolerance


Variable quality of service, packets may be delivered in the wrong order

Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 5 / 54 Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 6 / 54

The Internet is a Network of Networks Network Protocols

VU CS network Most computer network use the Internet Protocols


I Even if they are not connected to the Internet
TU Delft Univ. Twente
The base protocol: IP (Internet Protocol)
I Send packets of limited size (<8kB)
VU Chem network
Another ISP I Each packet is sent to an IP address
F Example IP address: 130.37.193.13
VU I IP offers no guarantee:
Surfnet
VU Physics network router F Packets may get lost
router F Packets may be delivered twice
F Packets may be delivered in the wrong order
F Packets may be corrupted during transfer
I Usually, programs do not use IP directly
Yet another ISP I All other Internet protocols are built over IP

Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 7 / 54 Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 8 / 54
UDP: User Datagram Protocol TCP: Transmission Control Protocol

UDP is very similar to IP: TCP establishes connections between pairs of machines
I Send/receive packets
I To communicate with a remote host, we must first connect to it.
I No guarantee TCP provides the illusion of a reliable data flow to the users
In UDP, “packets” are called “datagrams”
I Flows are split into packets, but the users doesn’t see it
Each datagrams is sent to an IP address and a port number TCP guarantees that the data sent will not be lost, unordered,
corrupted, etc.
I Example: IP=130.37.193.13 port=1234
I The sender gives numbers to packets so that the receiver can reorder
Ports allow to distinguish between several simultaneous programs on them.
the same machine I The receiver acknowledges received packets so that the sender can
I Program 1 uses port 1234 retransmit lost packets.
I Program 2 uses port 1235
Communication is bi-directional
I When a datagram is received, the operating system known which
program the datagram should be delivered to.
I The same connection can be used to send data in the two directions
I E.g., a request and its response

Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 9 / 54 Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 10 / 54

Network Layers – A Very Simplified View Table of Contents


User program User program

Establish connections 1 A Very Brief Introduction to Computer Networks


Split data streams into packets
Acknoledge received packets TCP TCP
Retransmit lost packets 2 IP Addressing and Name Resolution
Reorder packets

Router 3 UDP Sockets


Find how to reach a given host
If on the same network, easy IP IP IP
Otherwise send to a router 4 TCP Sockets

5 I/O Multiplexing
Transform packets into
electrical signals
Make sure signals Ethernet Ethernet Ethernet
do not interfere with
6 Server Structures
each other

Network Programming 2. Programming with sockets A Very Brief Introduction to Computer Networks 11 / 54 Network Programming 2. Programming with sockets IP Addressing and Name Resolution 12 / 54
Big-endian, Little-endian and Network Ordering IP Address Conversion Functions

Computers can represent numbers in little-endian or big-endian byte


ordering Humans like to represent IP addresses in dotted notations
I Depending if the most significant bits are at the beginning or the end (128.93.11.52), computers prefer a 32-bit integer.
of a bit sequence.
F Big-endian: PowerPC, (Ultra)Sparc, . . .
You can convert one into the other:
F Little-endian: Alpha, i386, . . . #include <arpa/inet.h>
in_addr_t inet_addr(const char *dotted); /* Dotted to Network */
I When computers transmit data to each other, they must stick to a char *inet_ntoa(struct in_addr network); /* Network to Dotted */
standard
F Protocols like IP, UDP and TCP use the network byte ordering I in addr t is an unsigned 32-bit integer
To convert numbers from host to network ordering: I struct in addr is a structure containing an in addr t:
struct in_addr {
#include <netinet/in.h> in_addr_t s_addr;
uint16_t htons(uint16_t hvalue); /* Host to Network, 16 bits */ };
uint32_t htonl(uint32_t hvalue); /* Host to Network, 32 bits */
uint16_t ntohs(uint16_t hvalue); /* Network to Host, 16 bits */ I There are historic reasons why this is done that way. . .
uint32_t ntohl(uint32_t hvalue); /* Network to Host, 32 bits */

Network Programming 2. Programming with sockets IP Addressing and Name Resolution 13 / 54 Network Programming 2. Programming with sockets IP Addressing and Name Resolution 14 / 54

sockaddr in: the Unix Network Address Structure [1/2] sockaddr in: the Unix Network Address Structure [2/2]

Unix represents network addresses with a struct sockaddr


sin family: used to indicate which type of address is following.
I This structure is generic for all kind of networks
I For Internet addresses, we use sockaddr in: Always set it to AF INET.
struct sockaddr_in {
sin port: port number, in network byte ordering.
sa_family_t sin_family; /* set to AF_INET */ sin addr.s addr: IP address, in network byte ordering. To represent
in_port_t sin_port; /* Port number */ an unspecified IP address, set it to htonl(INADDR ANY).
struct in_addr sin_addr; /* Contains the IP address */
}; I This is useful, for example, when specifying the port number of a
struct sin_addr { socket: you usually do not need to specify its IP address because it is
in_addr_t s_addr; /* IP address in network ordering */ set to that of the hosting machine.
};

Network Programming 2. Programming with sockets IP Addressing and Name Resolution 15 / 54 Network Programming 2. Programming with sockets IP Addressing and Name Resolution 16 / 54
Domain Names Converting Domain Names into IP Addresses

Internet protocols are all based on IP addresses #include <netdb.h>


I But IP addresses are hard for humans to remember struct hostent *gethostbyname(const char *name);

The solution: Domain Names


I Much more readable: www.cs.vu.nl is the Web server of the computer
name: Domain name to be resolved
science department of the Vrije Universiteit in The Netherlands.
I Domain names cannot be used directly by network protocols struct hostent {
char *h_name; /* official name of host */
F Network protocols only use IP addresses char **h_aliases; /* alias list */
F But you can convert domain names into IP addresses int h_addrtype; /* host address type */
int h_length; /* length of address */
Domain name resolution is handled by the Domain Name Service char **h_addr_list; /* list of addresses */
(DNS) };
I Hundreds of thousands of servers around the world that cooperate to
resolve addresses I h addr list: A zero-terminated array of network addresses for the
I To learn more on how this works, go to the Distributed Systems course! host in network byte order.

Network Programming 2. Programming with sockets IP Addressing and Name Resolution 17 / 54 Network Programming 2. Programming with sockets IP Addressing and Name Resolution 18 / 54

Example use of gethostbyname() Table of Contents

#include <netdb.h> 1 A Very Brief Introduction to Computer Networks


int print_resolv(const char *name) {
struct hostent *resolv;
struct in_addr *addr;
2 IP Addressing and Name Resolution

resolv = gethostbyname(name);
if (resolv==NULL) { 3 UDP Sockets
printf("Address not found for %s\n",name);
return -1;
} 4 TCP Sockets
else {
addr = (struct in_addr*) resolv->h_addr_list[0];
printf("The IP address of %s is %s\n",name,inet_ntoa(*addr)); 5 I/O Multiplexing
return 0;
}
} 6 Server Structures

Network Programming 2. Programming with sockets IP Addressing and Name Resolution 19 / 54 Network Programming 2. Programming with sockets UDP Sockets 20 / 54
UDP Socket Functions socket(): create a socket

UDP Client UDP Server


socket()
socket() creates a new socket:
bind() #include <sys/types.h>
#include <sys/socket.h>
socket() int socket(int domain, int type, int protocol);
recvfrom()
To create an Internet socket, use:
sendto() Data (req I domain = AF INET
ue st) I type = SOCK DGRAM for UDP or SOCK STREAM for TCP
I protocol = 0
) The returned value is the socket identifier (or -1 in case of error)
Data (reply sendto()
recvfrom()

close() close()

Network Programming 2. Programming with sockets UDP Sockets 21 / 54 Network Programming 2. Programming with sockets UDP Sockets 22 / 54

bind(): Affect an Address to a Socket Example use of socket() and bind()

bind() is used to specify the address of the socket: IP address and To create a UDP socket on port 1234:
port number.
I If you do not specify them, the system gives them a value int fd, err;
F IP address: the IP address of the running host (this is usually correct) struct sockaddr_in addr;
F Port number: any number (this can be correct or not depending on the
use of the socket) fd = socket(AF_INET,SOCK_DGRAM,0);
if (fd<0) { ... }
I Question: when do you need to specify a port number, and when can
you omit it? addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
#include <sys/types.h> addr.sin_addr.s_addr = htonl(INADDR_ANY);
#include <sys/socket.h>
int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen); err = bind(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (err<0) { ... }

I sockfd: the identifier of the socket


I my addr: a pointer to a struct sockaddr in containing the address
I addrlen: the size of a struct sockaddr in
For historic reasons, you are obliged to explicitly cast your struct
I Return value: 0 in case of success, -1 otherwise sockaddr in * into a struct sockaddr *

Network Programming 2. Programming with sockets UDP Sockets 23 / 54 Network Programming 2. Programming with sockets UDP Sockets 24 / 54
sendto(): Sending a UDP Datagram sendto() example

sendto() is used to send a UDP datagram: (the socket is created)


#include <sys/types.h> char msg[64];
#include <sys/socket.h> int err;
int sendto(int fd, const void *msg, size_t len, int flags, struct sockaddr_in dest;
const struct sockaddr *to, socklen_t tolen);
strcpy(msg,"hello, world!");

Ifd: the socket descriptor dest.sin_family = AF_INET;


Imsg: the message to be sent dest.sin_port = htons(1234);
I len: the length of the message dest.sin_addr.s_addr = inet_addr("130.37.193.13");
I flags: options, usually set to 0
err = sendto(fd, msg, strlen(msg)+1, 0, (struct sockaddr*) &dest,
I to: the destination address (IP address and port number!) sizeof(struct sockadddr_in));
I tolen: the size of a struct sockaddr in if (err<0) { ... }
+ Return value: the number of characters sent, or -1 in case of an error

Network Programming 2. Programming with sockets UDP Sockets 25 / 54 Network Programming 2. Programming with sockets UDP Sockets 26 / 54

recvfrom(): Waiting for an UDP Datagram recvfrom() example

recvfrom() blocks the program until a UDP datagram is received


#include <sys/types.h>
#include <sys/socket.h> (the socket is created and bound to a well-known port)
int recvfrom(int fd, void *buf, size_t len, int flags,
struct sockaddr *from, socklen_t *fromlen); char msg[64];
int len, flen;
struct sockaddr_in from;
Ifd: the socket descriptor
Ibuf: a buffer where the message will be copied flen = sizeof(struct sockaddr_in);
len = recvfrom(fd, msg, sizeof(msg), 0,
I len: the size of the buffer
(struct sockaddr*) &from, &flen);
I flags: usually set to 0 if (len<0) { ... }
I from: a structure where the origin address of the datagram will be printf("Received %d bytes from host %s port %d: %s", err,
inet_ntoa(from.sin_addr), ntohs(from.sin_port), msg);
copied
I fromlen: a pointer to an integer containing the size of from

+ Return value: the number of characters received, or -1 in case of an


error

Network Programming 2. Programming with sockets UDP Sockets 27 / 54 Network Programming 2. Programming with sockets UDP Sockets 28 / 54
close(): Closing a Socket Table of Contents

1 A Very Brief Introduction to Computer Networks

Sockets must be closed when they are no longer used 2 IP Addressing and Name Resolution
#include <unistd.h>
int close(int fd); 3 UDP Sockets

fd: the socket descriptor 4 TCP Sockets


+ Return value: 0 for success, -1 for error
5 I/O Multiplexing

6 Server Structures

Network Programming 2. Programming with sockets UDP Sockets 29 / 54 Network Programming 2. Programming with sockets TCP Sockets 30 / 54

TCP Socket Functions Some Functions are the Same as in UDP


TCP Client TCP Server
socket()

bind() socket: creates a socket


I To create a TCP socket:
listen()
socket() fd = socket(AF_INET, SOCK_STREAM, 0);
Connecti accept()
connect() on establi
shment
Data (request) bind: to specify the address of a socket
write() read() I Only useful for server sockets (client sockets do not need to be
addressed anyway)
Data (reply) write() I Exactly like UDP sockets
read()

Disconnection
close() read()

close()

Network Programming 2. Programming with sockets TCP Sockets 31 / 54 Network Programming 2. Programming with sockets TCP Sockets 32 / 54
listen(): Setting a Socket to Server Mode [1/2] listen(): Setting a Socket to Server Mode [2/2]

TCP sockets are created by default as client sockets


I A client socket cannot receive incoming connections Interface is simple:
Server sockets need to maintain more state #include <sys/socket.h>
I TCP establishes connections thanks to the three-way handshake: int listen(int fd, int backlog);
1 The client sends a connection request
2 The server answers (positively in this case) Ifd: the socket descriptor
3 The client acknowledges the server’s answer Ibacklog: the size of the buffer (often set to 5)
I Server sockets must allocate resources for handling connections + Return value: 0 for success, -1 in case of an error
between phases 2 and 3.
Note: backlog is not a limit on the number of concurrent established
F Once the connection is established, these resources are released
+ There can be several concurrent connection requests! connections!
I To convert a client socket to a server socket, use listen The Stevens book has a very interesting discussion on the backlog
F And indicate how many not-yet-connected connections can be parameter (page 93-99)
supported in parallel
F If this number is exceeded, the server will refuse connections

Network Programming 2. Programming with sockets TCP Sockets 33 / 54 Network Programming 2. Programming with sockets TCP Sockets 34 / 54

accept(): Waiting for an Incoming Connection accept() Example

accept blocks the program until an incoming connection is received


I When a connection is received, connect creates a new socket int sock, newsock, res;
sockaddr_in client_addr;
descriptor dedicated for this connection socklen_t addrlen;
I The new socket is used to communicate with the client
I The first socket is immediately ready to wait for other connections (the socket sock is created and bound)

#include <sys/types.h> res = listen(sock,5);


#include <sys/socket.h> if (res<0) { ... }
int accept(int fd, struct sockaddr *addr, socklen_t *addrlen);
addrlen = sizeof(struct sockaddr_in);
newsock = accept(sock,(struct sockaddr *) &client_addr, &addrlen);
Ifd: the socket descriptor if (newsock<0) { ... }
Iaddr: a pointer to a sockaddr in structure where the address of the else {
printf("Received connection from %s!\n",
client will be copied inet_ntoa(client_addr.sin_addr));
I addrlen: a pointer to an integer containing the size of addr }
+ Return value: the descriptor of the newly created socket or -1 in case
of an error

Network Programming 2. Programming with sockets TCP Sockets 35 / 54 Network Programming 2. Programming with sockets TCP Sockets 36 / 54
connect(): Connecting a TCP Socket write(): Sending Data to a Socket

write works the same for sending data to a TCP socket or writing to
Clients initiate connections to servers thanks to connect: a file
#include <sys/types.h> #include <unistd.h>
#include <sys/socket.h> ssize_t write(int fd, const void *buf, size_t count);
int connect(int fd, const struct sockaddr *serv_addr,
socklen_t addrlen);
Ifd: socket descriptor
Ibuf: buffer to be sent
I fd: the socket descriptor I count: size of the buffer
I serv addr: a pointer to a struct sockaddr in containing the + Return value: the number of bytes sent, or -1 in case of an error
address where to connect to
F Obviously, you must specify the destination IP address and port number Attention: when writing to a socket, write may send less bytes than
I addrlen: the size of a struct sockaddr in
requested
I Due to limits in internal kernel buffer space
+ Return value: 0 in case of success, or -1 in case of an error
⇒ Always check the return value of write, and resend the
Question: can you guess conditions which create an error? non-transmitted data
F And/or use the writen function from the Stevens book (page 78)

Network Programming 2. Programming with sockets TCP Sockets 37 / 54 Network Programming 2. Programming with sockets TCP Sockets 38 / 54

read(): Reading Data from a Socket close(): Closing a TCP Socket

read() blocks the program until receiving data from the socket
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
To stop sending data to a socket, use close():
Ifd: socket descriptor #include <unistd.h>
I buf: buffer where to write the read data int close(int fd);
I count: size of buf

+ Return value: the number of bytes read, or -1 in case of an error This sends an end-of-file message to the other party
I When receiving an EOF, read returns 0 byte
Attention: when reading from a socket, read() may read less bytes I Subsequent reads and writes will return errors
than requested
I It delivers the data that have been received
I This does not mean that the stream of data is finished, there may be
more to come
I The end-of-file is notified to the reader by read()ing 0 byte

Network Programming 2. Programming with sockets TCP Sockets 39 / 54 Network Programming 2. Programming with sockets TCP Sockets 40 / 54
shutdown(): Asymmetric Disconnection Table of Contents

Sometimes you may want to tell the other party that you are finished,
but let it finish before closing connection 1 A Very Brief Introduction to Computer Networks
#include <sys/socket.h>
int shutdown(int fd, int how); 2 IP Addressing and Name Resolution
I how: SHUT WR for stopping writing, SHUT RD for stopping reading
I When one party has closed the connection, the other can still write
3 UDP Sockets
data (and then close the connection as well)
4 TCP Sockets
To initiate a disconnection To receive a disconnection
shutdown(fd,SHUT WR) read() receives an EOF 5 I/O Multiplexing
Keep on reading the last data Keep on writing the last data
6 Server Structures
Until receiving an EOF Then close() the socket
close() the socket

Network Programming 2. Programming with sockets TCP Sockets 41 / 54 Network Programming 2. Programming with sockets I/O Multiplexing 42 / 54

I/O Multiplexing select(): I/O Multiplexing [1/3]

How can a program handle multiple file descriptors simultaneously? select() monitors several file descriptors simultaneously
I accept() and read() block programs until something is received
#include <sys/select.h>
I How can you wait for connections/data from multiple sockets? int select(int n, fd_set *readfds, fd_set *writefds,
Several methods: fd_set *exceptfds, struct timeval *timeout);
I Use multiple processes
F Resource consuming, hard to program In: the highest-numbered file descriptor, plus 1
I Use non-blocking I/O Ireadfs: a list of file descriptors to monitor for reading
I writefs: a list of file descriptors to monitor for writing
F It works for read() but not for accept()
I exceptfs: a list of file descriptors to monitor for exceptions
I select() monitors multiple file descriptors
I timeout: a duration after which select() returns anyway. Set it to 0
F It blocks the program until one of them is ready for reading or writing
for no timeout.
I poll() is similar to select() + Return value: the number of (i.e., how many) descriptors ready for
F With additional information about streams I/O, or 0 in case of timeout, or -1 in case of an error
F We won’t discuss it here

Network Programming 2. Programming with sockets I/O Multiplexing 43 / 54 Network Programming 2. Programming with sockets I/O Multiplexing 44 / 54
select(): I/O Multiplexing [2/3] select(): I/O Multiplexing [3/3]

int nb, fd1=5, fd2=8;


char buf[1024];
fd set is a bitset representing a list of file descriptors fd_set rset;
I Do not manipulate fd set directly, always use special macros:
while (1) {
FD_ZERO (fd_set *set); /* clears all bits */ FD_ZERO(&rset);
FD_SET (int fd, fd_set *set); /* turns on bit fd */ FD_SET(fd1, &rset);
FD_CLR (int fd, fd_set *set); /* turns off bit fd */ FD_SET(fd2, &rset);
FD_ISSET(int fd, fd_set *set); /* checks if bit fd is set */
nb = select(20,&rset, NULL, NULL, NULL);
if (nb<=0) { ... }
select() modified the contents of readfs, writefs and exceptfs if (FD_ISSET(fd1,&rset)) {
bzero(buf,1024);
After select(), file descriptors that are ready for use are turned on nb = read(fd1,buf,1024);
in their set if (nb<0) { ... }
if (nb==0) printf("Received EOF on fd1!\n");
I Non-ready descriptors are turned off
else printf("Received data on fd1: %s\n");
To wait for a socket to be ready to accept(), put it in the read set }
if (FD_ISSET(fd2,&rset)) { ... }
}

Network Programming 2. Programming with sockets I/O Multiplexing 45 / 54 Network Programming 2. Programming with sockets I/O Multiplexing 46 / 54

Table of Contents Server Structures

1 A Very Brief Introduction to Computer Networks Often, a server accepts connections to one (TCP) socket
But it wants to process several requests simultaneously
2 IP Addressing and Name Resolution I Better use of the server’s resources
I Incoming requests can start being processed immediately after reception
3 UDP Sockets Depending on its nature, a server can receive between 0 and dozens
of thousands of requests per second
4 TCP Sockets Several server structures can be used:
I Iterative (i.e., not concurrent)
I One child per client
5 I/O Multiplexing I Prefork
I Select loop
6 Server Structures I Many other variants. . .

Network Programming 2. Programming with sockets Server Structures 47 / 54 Network Programming 2. Programming with sockets Server Structures 48 / 54
Iterative Servers One Child Per Client [1/2]

An iterative server treats one request after the other A new process is created to handle each connection
int fd, newfd; void sig_chld(int) {
while (1) { while (waitpid(0,NULL,WNOHANG)>0) {}
newfd = accept(fd, ...); signal(SIGCHLD,sig_chld);
treat_request(newfd); }
close(newfd);
} int main() {
int fd, newfd, pid;
I Simple signal(SIGCHLD,sig_chld);
I Potentially low resource utilization while (1) {
F If treat request() does not utilize all the CPU, resources are wasted newfd = accept(fd, ...);
if (newfd<0) continue;
I Potentially long waiting queue of incoming connections waiting to be pid = fork();
accept()ed if (pid==0) { treat_request(newfd); exit(0); }
F Increased request treatment latency else { close(newfd); }
F If the queue increases, the server may start rejecting incoming }
}
connections

Network Programming 2. Programming with sockets Server Structures 49 / 54 Network Programming 2. Programming with sockets Server Structures 50 / 54

One Child Per Client [2/2] Preforked [1/2]

The server first creates a pool of processes dedicated to treating


This is the most common type of concurrent server requests
I Several requests are treated simultaneously #define NB_PROC 10
I Incoming requests are accepted and treated immediately void recv_requests(int fd) { /* An iterative server */
int f;
It may not be suitable for highly loaded servers while (1) {
I fork() takes a lot of time f=accept(fd,...);
I You cannot limit the number of concurrent requests treat_request(f);
close(f);
Remark: you can make one thread per client on the same model }
}
Questions:
I Why is the signal call necessary? int main() {
I What happens if treat request() modifies a global variable? int fd;
for (int i=0;i<NB_PROC;i++) { /* Create NB_PROC children */
F For example: to increment a request counter. . . if (fork()==0) recv_requests(fd);
I How can you obtain the desired effect? }
while (1) pause(); /* The parent process does nothing */
}

Network Programming 2. Programming with sockets Server Structures 51 / 54 Network Programming 2. Programming with sockets Server Structures 52 / 54
Preforked [2/2] Select Loop

Highly loaded servers are often structured as preforked servers A single process manages multiple connections simultaneously thanks
IConcurrent request treatment to select()
I No waisted time to fork() each time a connection is received I This is quite difficult to do correctly
I You can limit the number of concurrent requests I You must split request treatment into a set of non-blocking stages
+ For example, the Apache Web server is structured that way I You must maintain a list of data structure containing the current state
There are variants to this model of each concurrent request
F Which stage it is in
I With a thread pool instead of a process pool F All internal data it needs
Not all systems allow multiple processes to accept() the same
socket simultaneously Implementing a select loop server is left to the students to exercise
I You must synchronize accesses to accept() :-)
+ lock mutex(); accept(); unlock mutex(); For example, the Squid Web cache is implemented as a select loop

Network Programming 2. Programming with sockets Server Structures 53 / 54 Network Programming 2. Programming with sockets Server Structures 54 / 54

You might also like