title: Killing entire process tree in ruby
body: <p>So I'm working on some background task and I ended up having to spawn a child processes (using a binary provided by another team). At some point I want to stop such a process if it times out.</p>
  <p>Seems straightforward enough.</p>
  <pre><code>def run!(command, timeout)
    Timeout.timeout(timeout) do
      stdin, stdout, wait_thr = Open3.popen2e(command)
      @pid = wait_thr.pid
  
      # ... boring and irrelevant...
    end
  rescue Timeout::Error
    Process.kill 'TERM', @pid
    Process.wait pid
  
    raise
  end
  </code></pre>
  <p>Now I also quite like prepending my command with a call to <code>time</code>. Nice logs and all. This makes a command something like this (MacOS)</p>
  <pre><code>gtime -f 'Time spent %E memory used %M' some/binary --with parameters&quot; 
  </code></pre>
  <p>And so my process tree becomes something like this</p>
  <pre><code>ruby (my background job)
   \__ gtime
        \__ some/binary
  </code></pre>
  <p>Of course now when I kill the child process, only <code>gtime</code> is killed, the binary lives on.</p>
  <ol>
  <li>If I had control over the executable I'm using as the immediate child, I could probably handle <code>TERM</code> and kill its immediate children processes. But it's <code>time</code>/<code>gtime</code> so I obviously don't. But maybe there's some arcane parameter?</li>
  <li>The <a href="https://docs.ruby-lang.org/en/2.0.0/Process.html#method-c-kill" rel="nofollow noreferrer">docs</a> mention process groups but of course the children share the same process group as my parent process. Is there a way to spawn a process in a new process group thus making the &quot;kill the entire process group&quot; option viable?</li>
  </ol>
  <p>I also could probably parse the <code>ps</code> output, build a process tree and traverse it killing processes one-by-one, but it seems a bit overkill (sorry). Is there something really basic I'm missing here?</p>