C/Zombies
From Attie's Wiki
(Difference between revisions)
(2 intermediate revisions by 2 users not shown) |
Latest revision as of 17:06, 14 February 2013
The code below will quickly tidy up after zombie children, and at the same time check for incoming data.
- Assume
sock
is the file descriptor that you wish to read from
-
children
is incremented when you callfork()
/* tidy up after children, but accept new data if its there! */ while (children) { int pid, status, read; struct timeval timeout; fd_set toset; /* check if any children have become zombies! */ pid = waitpid(-1,&status,WNOHANG | WUNTRACED); if (pid > 0) { children--; printf("*** Child Died *** PID: %-6d Status: %-3d Children: %-2d\n",pid,WEXITSTATUS(status),children); /* if there are no children left, will break if there are more zombie children will tidy up before looking for data */ continue; } /* timeout on the socket every 0.5sec */ memset(&timeout,0,sizeof(timeout)); timeout.tv_usec = 500000; FD_ZERO(&toset); FD_SET(sock,&toset); /* check if there is data in the socket to be read... */ if ((read = select(sock+1,&toset,NULL,NULL,&timeout)) == -1) { perror("select()"); break; } else if (read != 0) { /* something can be read! */ break; } }