Using TCP Through Sockets
Using TCP Through Sockets
Using TCP Through Sockets
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
client s<br />
client s<br />
client s<br />
parent<br />
child<br />
child<br />
finger<br />
stdout<br />
stderr<br />
1<br />
2<br />
1<br />
2<br />
1<br />
2<br />
1<br />
2<br />
Figure 1: file descriptors in a forking server are inherited by the child process (top<br />
figure). In the second figure, the child process has called dup2 to connect file descriptors<br />
1 and 2 which normally correspond to standard output and standard error to the network<br />
socket. In the final figure, the child has called execl and the local finger process runs, sending<br />
its standard output over s.<br />
Accept takes a socket s on which one is listening and returns a new socket to which<br />
a client has just connected. If no clients have connected, accept will block until one<br />
does. accept returns −1 on an error.<br />
For <strong>TCP</strong>, addr should be a struct sockaddr in *. addrlenp must be a pointer<br />
to an integer containing the value sizeof (struct sockaddr in). accept will adjust<br />
*addrlenp to contain the actual length of the struct sockaddr it copies into<br />
*addr. In the case of <strong>TCP</strong>, all struct sockaddr in’s are the same size, so *addrlenp<br />
shouldn’t change.<br />
The finger daemon makes use of a few more Unix system calls which, while not networkspecific,<br />
are often encountered in network servers. With fork it creates a new process. This<br />
new process calls dup2 to redirect its standard output and error over the accepted socket.<br />
Finally, a call to execl replaces the new process with an instance of the finger program.<br />
Finger inherits its standard output and error, so these go straight back over the network to<br />
the client.<br />
• int fork (void);<br />
fork creates a new process, identical to the current one. fork returns twice: in the old<br />
process, fork returns a process ID of the new process. In the new or “child” process,<br />
fork returns 0. fork returns −1 if there is an error.<br />
• int dup2(int oldfd, int newfd);<br />
dup2 closes file descriptor number newfd, and replaces it with a copy of oldfd. When<br />
the second argument is 1, this changes the destination of the standard output. When<br />
that argument is 2, it changes the standard error.<br />
10