Chaitanya
Chaitanya

Reputation: 3469

killing a child process (after fork) once its execution is done

I m writing a simple web server. The program in simplified form is as follows

while(1)
{
     // accepting the connection.
     accept();

     pid = fork();

     if(pid == 0)
     { 
          // performing some operations
          _exit(EXIT_SUCCESS);

     } else {

          sleep(1);
     }
}

So once the child process executes it should terminate, and the parent process should continue accepting the connection. But, for me the child process is not getting terminated and even it(child) is also accepting the connections. Am I doing any mistake here.

I am able to see the process (child) not being killed using.

top -U <username>

I need help on this. Thanks in advance. :)

Upvotes: 2

Views: 2891

Answers (2)

Chaitanya
Chaitanya

Reputation: 3469

First of all thanks everyone for helping me out. I got the mistake in my code. :)

The problem was once after accepting the connection and forking, within the child process I got to close() the socket connection using the file descriptor used in accept method like

accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

then close(sockfd) should be called within the child process. Since, it was not being closed in the child process, the socket was alive for accept() connections. So, nevertheless _exit() was given the child process won't be terminated until the associated socket file descriptor is closed.

along with this within the parent process we got to call wait() or waitpid() depending on your need for the child process to be removed from the process table and avoiding its zombie state.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

The parent process has to call wait to "reap" the child process.

The reasons you need to "wait" for the children is because there are still resources left after a process exits, for the exit code of the child process. What wait (and its sibling system calls) are doing is not only waiting for child processes to end, but also get the exit code so the child process can be cleaned up properly by the operating system. If the parent process doesn't wait for all child processes to exit before itself exits, then all child processes becomes orphaned, and the process with process id 1 is set as their parent.

Upvotes: 3

Related Questions