Consider the following simple server in the internet domain using TCP. How I can
ID: 3851370 • Letter: C
Question
Consider the following simple server in the internet domain using TCP. How I can add a SIGCHLD handler to the SPECIFIC program below, to reap zombie processes in C?
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
pid_t pid;
int status;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided ");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
while (1) {
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
if((pid=fork())== -1)
{
pid = wait(&status);
close(newsockfd);
continue;
}
else if(pid>0)
{
//wait(NULL);
close(newsockfd);
continue;
}
while(1) {
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
if (n == 0) {printf("This Client is gone "); break;}
printf("Here is the message: %s ",buffer);
n = write(newsockfd, buffer, strlen(buffer));
if (n < 0) error("ERROR writing to socket");
}
}
return 0;
}
Explanation / Answer
this is all pointless. If the parent simply ignores SIGCHLD, the children are silently reaped and won't turn into zombies
you are using like this. then you will get
down vote
static void child_handler(int sig) { pid_t pid; int status; /* EEEEXTEERMINAAATE! */ while((pid = waitpid(-1, &status, WNOHANG)) > 0) ; } /* Establish handler. */ struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = child_handler; sigaction(SIGCHLD, &sa, NULL);