12 December 2006

Killing System Processes in Ruby

So I have recently had the need to create system process and kill them at times. I have never done this in ruby and it turned out to be fairly easy. In fact, like many things in ruby it was much easier than I was trying to make it. The real problem I was having was trying to figure out what the pid of the system process was. Process.fork returned the pid of the child ruby process that was forked, not the system call that was made inside the fork block, or so I thought. It turns out if you fork and then exec, the pid returned from the fork is the pid of the exec’ed process. This is of course how it should work, I just wanted it to be more tricky than that for some reason. Here is the little class I wrote to test it out.

class ExternalProcesses
def initialize
@pids = []

def run_command(cmd)
pid = Process.fork do
@pids << pid =" @pids.pop" e =" ExternalProcesses.new">
During the ’sleep 10′ you can verify that this works as expected by opening another terminal and looking at your systems process list.