There are a few differences between exit() and _exit() that become significant when fork(), and especially vfork(), is used.
The basic difference between exit() and _exit() is that the former performs clean-up related to user-mode constructs in the library, and calls user-supplied cleanup functions, whereas the latter performs only the kernel cleanup for the process.
In the child branch of a fork(), it is normally incorrect to use exit(), because that can lead to stdio buffers being flushed twice, and temporary files being unexpectedly removed. In C++ code the situation is worse, because destructors for static objects may be run incorrectly. (There are some unusual cases, like daemons, where the parent should call _exit() rather than the child; the basic rule, applicable in the overwhelming majority of cases, is that exit() should be called only once for each entry into main.)
In the child branch of a vfork(), the use of exit() is even more dangerous, since it will affect the state of the parent process.
Sunday, August 22, 2010
The exec() system call
The exec() system call
The exec() functions replace a current process with another created according to the arguments given.
The syntax of these functions is as follows:
#include
char *env[];
int execl(const char *path, const char *arg0, ..., (char *)0);
int execv(const char *path, const char *argv[]);
int execlp(const char *path, const char *arg0, ..., (char *)0);
int execvp(const char *path, const char *argv[]);
int execle(const char *path, const char *arg0, ... , (char *)0, const char *env[]);
int execve(const char *path, const char *argv[], const char *env[]);
The program given by the path argument is used as the program to execute in place of what is currently running. In the case of the execl() the new program is passed arguments arg0, arg1, arg2,... up to a null pointer. By convention, the first argument supplied (i.e. arg0) should point to the file name of the file being executed. In the case of the execv() programs the arguments can be given in the form of a pointer to an array of strings, i.e. the argv array. The new program starts with the given arguments appearing in the argv array passed to main. Again, by convention, the first argument listed should point to the file name of the file being executed. The function name suffixed with a p (execlp() and execvp())differ in that they will search the PATH environment variable to find the new program executable file. If the executable is not on the path, and absolute file name, including directories, will need to be passed to the function as a parameter. The global variable environ is available to pass a value for the new program environment. In addition, an additional argument to the exec() functions execle() and execve() is available for passing an array of strings to be used as the new program environment.
Examples to run the ls command using exec are:
const char *argv[] = ("ls", "-lrt", 0);
const char *env[] = {"PATH=/bin:/usr/bin", "TERM=console", 0};
execl("/bin/ls", "ls", "-lrt", 0);
execv("/bin/ls", argv);
execlp("ls", "ls", "-lrt", 0);
execle("/bin/ls", "ls", "-lrt", 0, env);
execvp("ls", argv);
execve("/bin/ls", argv, env);
The exec() functions replace a current process with another created according to the arguments given.
The syntax of these functions is as follows:
#include
char *env[];
int execl(const char *path, const char *arg0, ..., (char *)0);
int execv(const char *path, const char *argv[]);
int execlp(const char *path, const char *arg0, ..., (char *)0);
int execvp(const char *path, const char *argv[]);
int execle(const char *path, const char *arg0, ... , (char *)0, const char *env[]);
int execve(const char *path, const char *argv[], const char *env[]);
The program given by the path argument is used as the program to execute in place of what is currently running. In the case of the execl() the new program is passed arguments arg0, arg1, arg2,... up to a null pointer. By convention, the first argument supplied (i.e. arg0) should point to the file name of the file being executed. In the case of the execv() programs the arguments can be given in the form of a pointer to an array of strings, i.e. the argv array. The new program starts with the given arguments appearing in the argv array passed to main. Again, by convention, the first argument listed should point to the file name of the file being executed. The function name suffixed with a p (execlp() and execvp())differ in that they will search the PATH environment variable to find the new program executable file. If the executable is not on the path, and absolute file name, including directories, will need to be passed to the function as a parameter. The global variable environ is available to pass a value for the new program environment. In addition, an additional argument to the exec() functions execle() and execve() is available for passing an array of strings to be used as the new program environment.
Examples to run the ls command using exec are:
const char *argv[] = ("ls", "-lrt", 0);
const char *env[] = {"PATH=/bin:/usr/bin", "TERM=console", 0};
execl("/bin/ls", "ls", "-lrt", 0);
execv("/bin/ls", argv);
execlp("ls", "ls", "-lrt", 0);
execle("/bin/ls", "ls", "-lrt", 0, env);
execvp("ls", argv);
execve("/bin/ls", argv, env);
TCP Clients and Servers
The general order of library calls for a TCP client is as follows:
socket()
connect()
send() and/or recv()
close()
The general order of library calls for a TCP server is as follows:
socket()
bind()
listen()
accept()
send() and/or recv()
close()
Socket Address Structures
Internet socket addresses are stored in 16-byte structures of the type sockaddr_in defined as follows:
struct sockaddr_in{
short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
For Internet applications, the sin_family member is always AF_INET, the sin_port member is a 16-bit port number, and the sin_addr member is a 32-bit IP address. The in_addr structure has the following form
struct in_addr {
unsigned long s_addr;
};
Note that the in_addr struct is exactly 4 bytes long, which is the same size as an IP address. The IP address and port number are always stored in network (big-endian) byte order. For example:
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(9999)
sin.sin_addr.s_addr = inet_addr("128.227.224.3");
In the above code example, the structure sin holds the IP address 128.227.224.3, and references the port number 9999. Two utility functions are used to set these values. The function htons returns the integer argument passed into it in network byte order. The function inet_addr converts the string argument from a dotted-quad into a 32-bit integer. Its return value is also in network byte order.
TCP Library Calls
socket:
The socket library call has the following prototype:
int socket(int family, int type, int protocol);
In short, this function creates "an end point for communication". The return value from this function is a handle to a socket. This number is passed as a parameter to almost all of the other library calls. Since the focus of this document is on TCP/IP based sockets, the family parameter should be set to AF_INET. The type parameter can be either SOCK_STREAM (for TCP), or SOCK_DGRAM (for UDP). The protocol field is intended for specifying a specific protocol in case the network model support different types of stream and datagram models. However, TCP/IP only has one protocol for each, so this field should always be set to 0. Example to create a TCP socket:
int s;
s = socket(AF_INET, SOCK_STREAM, 0);
connect:
The connect library call has the following prototype:
int connect(int socket, struct sockaddr_in * address, int address_length);
This function establishes an Internet connection with the server at socket address address. The value of address_length is always sizeof(sockaddr_in). The connect function blocks until either the connection is successfully established, or an error occurs. If successful, the socket descriptor is now ready for reading and writing.
bind:
Before sending and receiving data using a socket, it must first be associated with a local source port and a network interface address. The mapping of a socket to a TCP/UDP source port and IP address is called a "binding". The bind function call is used to declare the mapping between the socket, the TCP/UDP source port, and the network interface device. The prototype for bind is as follows:
bind(int socket, struct sockaddr_in *address, int address_length);
The first argument is a socket handle (the number returned from the socket function call). The second argument is a sockaddr_in structure. The sin_port field of the address argument is the local source port number associated with this socket. That is, for every "send" operation with this socket, the source port field in the TCP/UDP header gets set with this value. If specifying an exact source port is not required, setting this value to INADDR_ANY(0) allows the operating system to pick any available port number. The sin_addr field specifies which network interface device to use. Since most hosts only have one network interface and only one IP address, this field should be set with the host's own IP address. However, the socket library provides no immediate way for a host to determine its own IP address! However, specifying the value of INADDR_ANY(0) in this field tells the operating system to pick any available interface and address.
The address of the sockaddr_in structure is passed into the bind call, so that the socket will now be ready to communicate with remote hosts. The third parameter passed to bind is the length of the sockaddr_in structure.
Example:
struct sockaddr_in sin;
int s;
s = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
sin.sin_port = htons(9999);
sin.sin_addr.s_addr = INADDR_ANY;
bind(s, (struct sockaddr *)&sin, sizeof(sin));
/* s is now a usable TCP socket. Source port is 9999 */
It is recommended that the return from bind be checked; bind will fail by returning -1 if the port that is being requested for use is already taken. When bind is called on a TCP socket, the socket is now ready for the connect or accept calls.
listen:
The server listens for incoming connection requests from clients. The prototype for listen is as follows:
listen(int socket, int backlog);
The first argument is a socket handle (the number returned from the socket function call). The second argument specifies the maximum number of connections that can be pending on the specified socket (typically set to a large value, such as 1024).
accept:
This is a blocking operation that does not return until a remote client has established a connection; when it completes, it returns a new socket that corresponds to this just-established connection. The prototype for accept is as follows:
int accept(int socket, struct sockaddr_in * address, int * addr_len);
The address argument contains the remote client's address. Note that when accept returns, the original socket that was given as argument still exists; it is used in a future invocation of accept.
send and recv:
Once a connection is established, the application processes invoke the following two operations to send and receive data:
int send(int socket, char * message, int msg_len, int flags);
int recv(int socket, char *buffer, int buf_len, int flags);
Both operations take a set of flags that control certain details of the operation.
Saturday, August 21, 2010
Packet exchange during a complete TCP connection
TCP protocol operations may be divided into three phases. Connections must be properly established in a multi-step handshake process (connection establishment) before entering the data transfer phase. After data transmission is completed, the connection termination closes established virtual circuits and releases all allocated resources.
A TCP connection is managed by an operating system through a programming interface that represents the local end-point for communications, the Internet socket. During the lifetime of a TCP connection it undergoes a series of state changes:
1. LISTEN : In case of a server, waiting for a connection request from any remote client.
2. SYN-SENT : waiting for the remote peer to send back a TCP segment with the SYN and ACK flags set. (usually set by TCP clients)
3. SYN-RECEIVED : waiting for the remote peer to send back an acknowledgment after having sent back a connection acknowledgment to the remote peer. (usually set by TCP servers)
4. ESTABLISHED : the port is ready to receive/send data from/to the remote peer.
5. FIN-WAIT-1
6. FIN-WAIT-2
7. CLOSE-WAIT
8. CLOSING
9. LAST-ACK
10. TIME-WAIT : represents waiting for enough time to pass to be sure the remote peer received the acknowledgment of its connection termination request. According to RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes.
11. CLOSED
TCP Connection Termination
As the saying goes, “all good things must come to an end”… and so it is with TCP connections. The link between a pair of devices can remain open for a considerable period of time, assuming that a problem doesn't force the connection to be aborted. Eventually, however, one or both of the processes in the connection will run out of data to send and will shut down the TCP session, or will be instructed by the user to do so.
Requirements and Issues In Connection Termination
Terminating a TCP connection requires four segments. This is because TCP supports a half-closed state. A half closed state is when one side of the connection sends a close (a FIN) which means that it will no longer send anything, but it is still listening for anything coming from the other side. The connection is completely terminated when the other side sends its FIN segment. Both of the FIN segments have to be acknowledged hence four segments. Furthermore, when the last of these acknowledgments has been sent, the sender has to keep their connection open for 4 minutes. This is known as the TIME_WAIT state.
The standard specifies that the client should wait double a particular length of time called the maximum segment lifetime (MSL) before finishing the close of the connection. The TCP standard defines MSL as being a value of 120 seconds (2 minutes). In modern networks this is an eternity, so TCP allows implementations to choose a lower value if it is believed that will lead to better operation.
There are two reasons for this four minute wait. The first is so that the final ACK can be resent if lost. The server will resend its FIN if it does not receive an ACK within a specified time (known as the retransmission timeout, RTO) and the client stays open long enough so that it will receive the retransmission if sent. The second reason is so that any duplicate segments that have been sent can time out before the port is used again for a new connection (all segments have a limited lifetime on the Internet, they will be simply discarded when this lifetime has expired).
There are two side effects to having a four minute wait. The first limits the number of transactions a client can process a second and the second is concerned with the amount of memory used by keeping a number of connections open.
There are only a finite number of ports available at any time. Since a port address is 16 bits the number of ports is 216 which is 65535. The number of reserved ports is 1023 (reserved for well known servers), so the number of ports available to a client at any time is 65535 - 1023 = 64512. The four minute wait combined with the finite number of available ports means that the number of transactions able to be processed by a client is limited to 64512 / 240 = 268 per second.
For each open connection, the operating system kernel of the host must maintain information about the connection in memory. In a typical Unix TCP/IP implementation each open connection requires 264 bytes of memory. If a host had to keep 64512 connections open at any time this equates to more than 17000000 bytes of memory!
Normal Connection Termination:
Just as TCP follows an ordered sequence of operations to establish a connection, it includes a specific procedure for terminating a connection. As with connection establishment, each of the devices moves from one state to the next to terminate the connection. This process is more complicated than one might imagine it needs to be. In fact, an examination of the TCP finite state machine shows that there are more distinct states involved in shutting down a connection than in setting one up.
The reason that connection termination is complex is that during normal operation, both of the devices are sending and receiving data simultaneously. Usually, connection termination begins with the process on just one device indicating to TCP that it wants to close the connection. The matching process on the other device may not be aware that its peer wants to end the connection at all. Several steps are required to ensure that the connection is shut down gracefully by both devices, and that no data is lost in the process.
Ultimately, shut down of a TCP connection requires that the application processes on both ends of the connection recognize that “the end is nigh” for the connection and stop sending data. For this reason, connection termination is implemented so that each device terminates its end of the connection separately. The act of closing the connection by one device means that device will no longer send data, but can continue to receive it until the other device has decided to stop sending. This allows all data that is pending to be sent by both sides of the communication to be flushed before the connection is ended.
Client
|
Server
|
||||
Start
State
|
Action
|
Transitions
To State
|
Start
State
|
Action
|
Transitions
To State
|
ESTABLISHED
|
Client Close Step #1 Transmit:
The application using TCP signals that the connection is no longer needed.
The client TCP sends a segment with the FIN bit set to request
that the connection be closed.
|
FIN-WAIT-1
|
ESTABLISHED
|
At this stage the server is still
in normal operating mode.
|
—
|
FIN-WAIT-1
|
The client,
having sent a FIN, is waiting for it to both be acknowledged
and for the serve to send its own FIN. In this state the client
can still receive data from the server but will no longer accept data
from its local application to be sent to the server.
|
—
|
ESTABLISHED
|
Client Close
Step #1 Receive and Step #2 Transmit: The server receives the client's
FIN. It sends an ACK to acknowledge the FIN. The
server must wait for the application using it to be told the other end
is closing, so the application here can finish what it is doing.
|
CLOSE-WAIT
|
FIN-WAIT-1
|
Client Close Step #2 Receive:
The client receives the ACK for its FIN. It must now wait
for the server to close.
|
FIN-WAIT-2
|
CLOSE-WAIT
|
The server waits for the application
process on its end to signal that it is ready to close.
|
—
|
FIN-WAIT-2
|
The client
is waiting for the server's FIN.
|
—
|
CLOSE-WAIT
|
Server Close
Step #1 Transmit: The server's TCP receives notice from the local
application that it is done. The server sends its FIN to the
client.
|
LAST-ACK
|
FIN-WAIT-2
|
Server Close Step #1 Receive
and Step #2 Transmit: The client receives the server's FIN
and sends back an ACK.
|
TIME-WAIT
|
LAST-ACK
|
The server is waiting for an
ACK for the FIN it sent.
|
—
|
TIME-WAIT
|
The client
waits for a period of time equal to double the maximum segment life
(MSL) time, to ensure the ACK it sent was received.
|
—
|
LAST-ACK
|
Server Close
Step #2 Receive: The server receives the ACK to its FIN
and closes the connection.
|
CLOSED
|
TIME-WAIT
|
The timer expires after double
the MSL time.
|
CLOSED
|
CLOSED
|
The connection is closed on the
server's end.
|
|
CLOSED
|
The connection
is closed.
|
CLOSED
|
The connection
is closed.
|
||
Simultaneous Connection Termination:
Just as it is possible for the normal connection establishment process to be changed if two devices decide to actively OPEN a connection to each other, it is also possible for two devices to try to terminate a connection simultaneously. This term “simultaneously” doesn't mean that they both decide to shut down at exactly the same time—variances in network delays mean nothing can be simultaneous on an internetwork anyway. It simply means that, in the example above, the client decides to shut down and sends a FIN, but the server sends its own FIN before the client's FIN shows up at the server.
Client
|
Server
|
||||
Start
State
|
Action
|
Transitions
To State
|
Start
State
|
Action
|
Transitions
To State
|
ESTABLISHED
|
Client Close Step #1 Transmit:
The application using TCP signals that the connection is no longer needed.
The TCP on the client sends the next segment with the FIN bit
set, indicating a request to close the connection.
|
FIN-WAIT-1
|
ESTABLISHED
|
Server Close Step #1 Transmit:
Before the server can receive the FIN sent by the client, the
application on the server also signals a close. The server also sends
a FIN.
|
FIN-WAIT-1
|
FIN-WAIT-1
|
Server Close
Step #1 Receive and Step #2 Transmit: The client has sent a FIN
and is waiting for it to be acknowledged. Instead, it receives the FIN
sent by the server. It acknowledges the server's close request with
an ACK and continues to wait for its own ACK.
|
CLOSING
|
FIN-WAIT-1
|
Client Close
Step #1 Receive and Step #2 Transmit: The server has sent a FIN
and is waiting for it to be acknowledged. Instead, it receives the FIN
sent by the client. It acknowledges the client's close request with
an ACK and continues to wait for its own ACK.
|
CLOSING
|
CLOSING
|
Client Close Step #2 Receive:
The client receives the ACK for its FIN.
|
TIME-WAIT
|
CLOSING
|
Server Close Step #2 Receive:
The server receives the ACK for its FIN.
|
TIME-WAIT
|
TIME-WAIT
|
The client
waits for a period of time equal to double the maximum segment life
(MSL) time. This gives enough time to ensure the ACK it sent
to the server was received.
|
—
|
TIME-WAIT
|
The server
waits for a period of time equal to double the maximum segment life
(MSL) time. This gives enough time to ensure the ACK it sent
to the client was received.
|
—
|
TIME-WAIT
|
The timer expires after double
the MSL time.
|
CLOSED
|
TIME-WAIT
|
The timer expires after double
the MSL time.
|
CLOSED
|
CLOSED
|
The connection
is closed.
|
—
|
CLOSED
|
The connection
is closed.
|
—
|
Subscribe to:
Posts (Atom)
