在 Ruby 中生成一个独立的线程或进程 [英] Spawning an independent thread or process in Ruby

查看:53
本文介绍了在 Ruby 中生成一个独立的线程或进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能在错误的方向接近这个,所以任何帮助将不胜感激.

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

我有一个 Ruby 脚本,其中包括启动可执行文件.我想启动这个可执行文件——当前正在使用系统"触发——然后继续执行脚本.当脚本完成时,我希望它退出但保持可执行文件运行.

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.

最初我有以下内容

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

# Continue working

但是 executable_to_run.exe 是一个阻塞的可执行文件,并且系统"在可执行文件完成运行之前不会退出(我不希望它这样做)

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.

所以我需要做的是触发executable_to_run.exe"并让它在后台运行.

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

我在 Windows 上使用 Ruby 1.8.7,这意味着 fork 未实现.我无法升级到 1.9,因为我需要首先解决内部和外部团队的依赖关系(并且不会很快完成).

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).

我试过了

  • 通过开始"运行进程命令,但这仍然阻止
  • 在可执行线程上调用 Thread.kill但它仍然需要可执行文件被杀

那么这是我可以在 Ruby 中做的事情吗,我只是遗漏了一些东西,或者我有问题,因为我不能使用 Fork?

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?

提前致谢

推荐答案

detunized 的答案应该适用于 Windows.这是跨平台的:

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

这篇关于在 Ruby 中生成一个独立的线程或进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆