Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spawning an independent thread or process in Ruby

I may be approaching this in the wrong direction, so any help would be appreciated.

I have a Ruby script which, amongst other things, starts up an executable. I want to start this executable - currently being triggered using system "" - and then continue on with the script. When the script finishes, I want it to exit but leave the executable running.

Originally I had the following

# Do some work
# Start the executable
system("executable_to_run.exe")

# Continue working

But executable_to_run.exe is a blocking executable, and system "" will not exit until the executable finishes running (which I don't want it to)

So I now have something like this (drastically cut down)

# Do some work
# Start the executable on it's one thread
Thread.new do
  system("executable_to_run.exe")
end

# Continue working

This works well in that my script can continue running while the thread runs the executable in the background. Unfortunately, when my script comes to exit, the executable thread is still running and it won't exit until the thread can exit. If I kill the executable the thread exits and the script exits.

So what I need to do is trigger "executable_to_run.exe" and simply leave it running in the background.

I'm using Ruby 1.8.7 on Windows, which means fork is unimplemented. I cannot upgrade to 1.9 as there are internal and external team dependencies which I need to resolve first (and which won't be done any time soon).

I've tried

  • Running the process via the 'start' command but this still blocks
  • Calling Thread.kill on the executable thread but it still requires the executable to be killed

So is this something I can do in Ruby and I'm just missing something or do I have a problem because I cannot use Fork?

Thanks in advance

like image 364
Lee Winder Avatar asked Apr 08 '11 10:04

Lee Winder


1 Answers

detunized's answer should work on windows. This one is cross-platform:

pid = spawn 'some_executable'
Process.detach(pid) #tell the OS we're not interested in the exit status
like image 87
steenslag Avatar answered Oct 04 '22 11:10

steenslag