I did a project last year, (recreate a little terminal like tcsh) and I used the fork()
because the execve()
kills the actual process, so I used the fork()
to execute the execve()
in the child and the parent wait for its dead.
Everything is clear here, now I'm working with sockets in C, and the project asks me to use select()
for the handling of fd and fork()
for the treatment. So, I have my infinte loop with the select()
and fork()
inside, I understand that we have to use fork()
for a better performance and speed. But I see that if I don't use waitpid()
or similar in the parent process, the child becomes zombie.
The question is, is there any way to don't have to wait for the child? What is the best way to scan the child processes while parent is doing other tasks? I mean, if I have to wait for the child in this case I don't improve the speed.
And other question, the child that becomes zombie consumes resources? Is it a problem to have zombie childs?
CodePudding user response:
fork()
spawns a child process; it isn’t required for network programming, but some network programs do it as a way to allow the code that handles a particular client to execute in parallel with the code (in the parent-process) that is accepting incoming TCP connections. Other approaches include spawning a thread to handle the client, or using asynchronous I/O, or using select()
and non-blocking I/O to handle the client in the same/single thread.
If you call fork()
and don’t want your child processes to become zombies, you will need to call waitpid()
on the child process at some point; otherwise the child process’s return-value will remain uncollected and you’ll have a zombie. However, you don’t have to call waitpid()
right away; and if you pass in the WNOHANG
argument you can avoid having waitpid()
block; instead, with WNOHANG
waitpid()
will return 0
immediately if the child process is still alive, and you can try calling it again later.
Having zombie processes is a problem, because if you keep generating them, eventually the processes-table will fill up with zombies and then you won’t be able to spawn any more processes.