Ruby code that opens a pipe to send data from a forked process to its parent and cleans up zombie threads
On and off, I’ve been working on a piece of Ruby code that uses phantomjs to automate web requests. Under certain situations, and heavy concurrent requests, it’s been known to leave behind zombie threads. In a previous blog post I shared some code that checks for zombie child threads and spawns a new process to remove them. For this particular scenario, the code was wrapped in Sinatra and served via Thin to provide web services. Restarting the parent process (in this case, Thin) was clearly unacceptable, so here is an alternative. The following code opens an IO pipe (which is shared with child processes), forks, executes the code, serializes the result, and writes it to the pipe. The parent process waits for it to finish, reads the result form the pipe, and checks for child processes left behind. If found, they are detached (assuming a parent pid of 1) and then killed.