1

Looking for a way to wait for the completion of all child processes, I found this code:

while true
    p "waiting for child processes"
    begin
        exited_pid = Process.waitpid(-1,Process::WNOHANG)
        if exited_pid and exited_pid > 0 then
            p "Process exited : #{exited_pid} with status #{$?.exitstatus }"
        end
        sleep 5
    rescue SystemCallError
        puts "All children collected!"
        break
    end
end

This looks like it works in a similar way to Unix-systems process management, as I read on tutorialspoint HERE.

So in summary, it looks like this code:

  1. Calls Process.waitpid, for any child process that exists. If no child process has exited, continue anyway.
  2. If a child process has exited, then notify the user. Otherwise sleep, and check again.
  3. When all child processes have exited an error is thrown, which is caught and the user is notified that processes are complete.

But looking at a similar question on waiting for child processes in C (Make parent wait for all child processes), which has as an answer:

POSIX defines a function: wait(NULL);. It's shorthand for waitpid(-1, NULL, 0);, which will block until all children processes exit.

I tested that Process.wait() in Ruby achieves pretty much the same thing as the more verbose code above.

What is the benefit of the more verbose code above? Or, which is considered a better approach to waiting for child processes? It seems in the verbose code that I would be able to wait for specific processes and listen for specific exit codes. But if I don't need to do this is there any benefit?

Also, regarding the more verbose code:

  1. Why does the call to Process.waitpid() throw an error if there are no more child processes?
  2. If more than 1 child process exists within the 5 second sleep period, it seems like there is a queue of completed processes and that Process.waitpid just returns the top member of the queue. What is actually happening here?
Zach Smith
  • 8,458
  • 13
  • 59
  • 133
  • 1
    What about `Process.waitall`? – Stefan Aug 17 '17 at 08:11
  • I didn't know about that one. Thanks! – Zach Smith Aug 17 '17 at 08:13
  • Have you read [the documentation](https://ruby-doc.org/core-2.4.1/Process.html)? Most, if not all, of your questions are answered there. But as a tl;dr: I don't see any benefit to the verbose code, besides the fact that it provides more verbose logging - which may be useful. (Although some process exit logging could be lost due to that `sleep(5)`!) – Tom Lord Aug 17 '17 at 08:16

0 Answers0