gpt4 book ai didi

ruby - Rakefile - 停止多任务中的每一个任务

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:03 24 4
gpt4 key购买 nike

我有一个使用 Flask 运行的应用程序,并使用 Compass 作为 css 预处理器。这意味着我需要启动 python 服务器和指南针进行开发。我做了一个我认为很聪明的 Rakefile,它可以从一个命令启动所有内容,并且只在一个终端窗口中运行所有内容。

一切正常,但问题是当我尝试停止一切时(使用 cmd + c),它只会终止 compass 任务,而 Flask 服务器继续运行。我怎样才能确保每个任务都停止了?或者是否有替代方案可以同时启动多个任务而不会出现此问题?

这是我的 rakefile,非常简单:

# start compass
task :compass do
system "compass watch"
end

# start the flask server
task :python do
system "./server.py"
end

# open the browser once everything is ready
task :open do
`open "http://127.0.0.1:5000"`
end

# the command I run: `$ rake server`
multitask :server => ['compass', 'python', 'open']

编辑

郑重声明,我使用的是 Makefile,一切都运行良好。但我改变了部分工作流程并开始使用 Rakefile,因此为了简单起见,我对所有内容进行了 Rakefile 处理并摆脱了 Makefile。

最佳答案

那是因为 system 为您的命令创建了新进程。为了确保它们与您的 ruby​​ 进程一起被杀死,您需要自己杀死它们。为此,您需要知道它们的进程 ID,system 不提供,但 spawn 提供。然后您可以等待它们退出,或者在您按下 ^C 时终止子进程。

一个例子:

pids = []

task :foo do
pids << spawn("sleep 3; echo foo")
end
task :bar do
pids << spawn("sleep 3; echo bar")
end

desc "run"
multitask :run => [:foo, :bar] do
begin
puts "run"
pids.each { |pid| Process.waitpid(pid) }
rescue
pids.each { |pid| Process.kill("TERM", pid) }
exit
end
end

如果您对其执行 rake run,命令将被执行,但是当您中止时,任务将发送 TERM 信号。仍然有一个异常(exception)使它达到顶层,但我想对于一个不打算发布的 Rakefile 来说并不重要。等待进程是必要的,否则 ruby​​ 进程将在其他进程之前完成并且 pid 丢失(或者必须从 ps 中挖掘出来)。

关于ruby - Rakefile - 停止多任务中的每一个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17721314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com