Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill process launched via thread

I have a headless application that uses sockets for communication. When launched, it remains active until sent a message telling it to quit (or it crashes, or is killed).

When unit testing this application using Ruby, I need to launch the process, interact with it (via sockets), and then kill it.

I thought I could do this using this pattern:

class TestServer < MiniTest::Unit::TestCase
  def setup
    @thread = Thread.new{ `#{MY_COMMAND}` }
  end

  def test_aaa
    # my test code
  end

  def teardown
    @thread.kill if @thread
  end
end

However, that teardown code kills the thread but does not kill the process launched by it.

How can I launch the process in a way that:

  1. Allows it to run in the background (immediately returns control to my Ruby test harness)
  2. Allows me to force kill the process later on, if need be.

I happen to be developing on OS X, but if possible I'd appreciate a generic solution that works across all OS where Ruby runs.

like image 572
Phrogz Avatar asked May 25 '26 12:05

Phrogz


1 Answers

You can use Process.spawn instead of threads and backticks:

class TestServer < MiniTest::Unit::TestCase
  def setup
    @pid = spawn "#{MY_COMMAND}"
  end

  def test_aaa
    # my test code
  end

  def teardown
    Process.kill('TERM', @pid) if @pid
  end
end
like image 141
Adrian Avatar answered May 27 '26 07:05

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!