Spawning an independent thread or process in Ruby

你离开我真会死。 提交于 2020-01-12 07:23:06

问题


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


回答1:


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



回答2:


I just tried and start doesn't block on Windows 7 x64 with Ruby 1.8.7.

system 'start notepad'
puts 'Exiting now...'

This is obviously Windows-specific.



来源:https://stackoverflow.com/questions/5593616/spawning-an-independent-thread-or-process-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!