S
Scottman
I am writing a server daemon that forks a child for every incoming
request. The child process terminates when the client closes the
connection. My problem is that I am unsure how to prevent the child
process from becoming defunct. Here is an over-simplified main
function...
int main(void) {
// Daemonize
int pid;
if ((pid = fork()) != 0) {
exit(0);
}
setsid();
if ((pid = fork()) != 0) {
exit(0);
}
// Assume this gets the socket descriptor, binds
// the socket and listens on given port.
int server_socket = create_server_socket(1234);
int client_socket;
while (1) {
// Assume this accepts a request to the server socket
client_socket = accept_socket_request(server_socket);
if (!fork()) {
// Child
// Assume this initiates a text interaction
// with the client, looping until the client
// enters 'exit'. Then it returns.
session();
// Close the client connection
shutdown(client_socket, 2);
// The child exits
exit(0);
} else {
// Parent
waitpid(-1, NULL, WNOHANG);
}
}
// Close the server socket
shutdown(server_socket, 2);
return 0;
}
What is happening is that if a client terminates a child process the
parent isn't aware until a new connection/process is made. I think
this is because of my placement of waitpid(). The result is that
there is a defunct child sitting around until a new connection is
made, then the defunct process is cleaned up. There is always at
least 1 defunct process lying around. How can I remedy this?
Thanks,
Scott
request. The child process terminates when the client closes the
connection. My problem is that I am unsure how to prevent the child
process from becoming defunct. Here is an over-simplified main
function...
int main(void) {
// Daemonize
int pid;
if ((pid = fork()) != 0) {
exit(0);
}
setsid();
if ((pid = fork()) != 0) {
exit(0);
}
// Assume this gets the socket descriptor, binds
// the socket and listens on given port.
int server_socket = create_server_socket(1234);
int client_socket;
while (1) {
// Assume this accepts a request to the server socket
client_socket = accept_socket_request(server_socket);
if (!fork()) {
// Child
// Assume this initiates a text interaction
// with the client, looping until the client
// enters 'exit'. Then it returns.
session();
// Close the client connection
shutdown(client_socket, 2);
// The child exits
exit(0);
} else {
// Parent
waitpid(-1, NULL, WNOHANG);
}
}
// Close the server socket
shutdown(server_socket, 2);
return 0;
}
What is happening is that if a client terminates a child process the
parent isn't aware until a new connection/process is made. I think
this is because of my placement of waitpid(). The result is that
there is a defunct child sitting around until a new connection is
made, then the defunct process is cleaned up. There is always at
least 1 defunct process lying around. How can I remedy this?
Thanks,
Scott