Is there a nice way out of an infinite loop? (I tried catching a SIGINT, but it won't let me clean up before exiting)
I'm doing a client-server. Each time a client connects, the server forks and designates a child to the client (this child will redirect stdin and stdout to a fd of a fifo or socket and then execl) In the server I am currently listening for clients in an infinite loop
for(;;)
{
listen_client();
create_child();
}
(more or less) The application works fine (each client can communicate perfectly with it's designated child-server). The problem comes on server-closure.
I was wondering if there was a nice way for the server to close (I'm not used on using endless loops, not sure if it's the right way and not sure if there is a nice way out).
I tried a sig_handler (sigaction), but I can't seem to make it work (ideally, I would close all fd, kill all childs and delete all fifos before exiting).
EDIT
with a global variable that keeps track of childs and a modification in sig_handler() it seems to be working, still not sure it's a nice way
(code in sig handler)
while(childs > 0)
{
pid = wait(NULL);
//cleanup mess of child
childs--
}
my doubts are: are children always dying automatically? or should I send a kill or something (in which case I'd guess I would need to keep track of every pid). is there a risk of creating zombies? is there a risk of entering an endless loop? (I never decrease "childs" other than here, I'm not sure if wait also counts the children dead long ago).
I know this "works", but I'd rather learn to do it the "right" way (if there is such thing)
You could disable async signal generation, create a signalfd(2) and poll(2) on that. That way you can handle all signals correctly and keep a linear program flow including correct cleanup. IMO this is a very convenient solution.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.