Hi,
In an example from Beej's guide to network programming there's the following piece of server code:
I think I kind of understand how the //reap dead processes block itself works, but how is it ever triggered from within the while(1) loop where the works is being done? I can understand how any present zombie processes may get reaped prior to entering the while(1) loop but not after.Code:void sigchld_handler(int s) { while(waitpid(-1, NULL, WNOHANG) > 0); } ... sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } while(1) { // main accept() loop sin_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \ &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", \ inet_ntoa(their_addr.sin_addr)); if (!fork()) { // this is the child process close(sockfd); // child doesn't need the listener if (send(new_fd, "Hello, world!\n", 14, 0) == -1) perror("send"); close(new_fd); exit(0); } close(new_fd); // parent doesn't need this }
Also if (sigaction(SIGCHLD, &sa, NULL) fails, tell us about it and exit the server all together. Isn't that a bit extreme or is such a thing only supposed to happen to mall-configured services?
Thanks,
heras
edit: I think this may be linux specific so I put it here.



LinkBack URL
About LinkBacks




