在 Ruby 中生成独立的线程或进程
我可能会朝错误的方向接近这个问题,所以任何帮助将不胜感激。
我有一个 Ruby 脚本,除其他外,它还启动一个可执行文件。我想启动这个可执行文件 - 当前正在使用系统“”触发 - 然后继续执行脚本。当脚本完成时,我希望它退出但保持可执行文件运行。
最初我有以下内容
# Do some work
# Start the executable
system("executable_to_run.exe")
# Continue working
但executable_to_run.exe是一个阻塞可执行文件,并且系统“”在可执行文件完成运行之前不会退出(我不希望它这样做)
所以我现在有这样的东西(大大减少)
# Do some work
# Start the executable on it's one thread
Thread.new do
system("executable_to_run.exe")
end
# Continue working
这有效很好的是,当线程在后台运行可执行文件时,我的脚本可以继续运行。不幸的是,当我的脚本退出时,可执行线程仍在运行,并且在线程退出之前它不会退出。如果我终止可执行文件,线程就会退出,脚本也会退出。
所以我需要做的是触发“executable_to_run.exe”并让它在后台运行。
我在 Windows 上使用 Ruby 1.8.7,这意味着 fork 尚未实现。我无法升级到 1.9,因为存在内部和外部团队依赖关系,我需要首先解决这些依赖关系(并且不会很快完成)。
我尝试过
- 通过“开始”运行该过程 命令,但这仍然阻止
- 在可执行线程上调用 Thread.kill 但它仍然需要可执行文件 被杀死
那么这是我可以在 Ruby 中做的事情,但我只是错过了一些东西,或者我是否因为无法使用 Fork 而遇到了问题?
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
detunized 的答案应该适用于 Windows。这是跨平台的:
detunized's answer should work on windows. This one is cross-platform:
我刚刚尝试过,
start
在使用 Ruby 1.8.7 的 Windows 7 x64 上不会阻塞。这显然是 Windows 特定的。
I just tried and
start
doesn't block on Windows 7 x64 with Ruby 1.8.7.This is obviously Windows-specific.