我现在有什么:
trap "SIGINT" do
case ENV["MODE"]
when "A"
...
when "B"
...
end
end
如果没有设置ENV["MODE"]
我想要没有陷阱,我会这样做:
trap "SIGINT" do
case
...
end
end if ENV["MODE"]
但是如果我想在特定值上传递陷阱呢?
trap "SIGINT" do
case ENV["MODE"]
when "A"
...
when "B"
...
when "C"
# here I want to really do a SIGINT
else
# or here
end
end
答案 0 :(得分:1)
请按照@ndn的建议来定义trap
或case
内的if
,而不是相反。
trap
注意:这只是一个概念验证!
在Process.kill('INT', Process.pid)
内拨打when "C"
只会再次被trap
抓住。您需要先取消trap
取消定义。来自documentation:
如果命令是“DEFAULT”或“SIG_DFL”,则为Ruby的默认处理程序 将被援引。
以下是一个例子:
trap "SIGINT" do
mode = %w(A B C D).sample
puts "Sigint with mode : #{mode}"
case mode
when "A"
puts "A, not exiting"
when "B"
puts "B, not exiting"
when "C"
puts "C, exiting"
trap "SIGINT", "DEFAULT"
Process.kill('INT', Process.pid)
else
puts "D, exiting"
trap "SIGINT", "DEFAULT"
Process.kill('INT', Process.pid)
end
end
while true
sleep 0.1
p "+1"
end
输出:
"+1"
"+1"
"+1"
^CSigint with mode : A
A, not exiting
"+1"
"+1"
"+1"
"+1"
"+1"
"+1"
^CSigint with mode : C
C, exiting
trap_sigint.rb:21:in `sleep': Interrupt
from trap_sigint.rb:21:in `<main>'
exit
这不是相同的信号,但如果您只想在模式为“C”或“D”时停止执行脚本,则可以使用exit
代替SIGINT
:< / p>
trap "SIGINT" do
mode = %w(A B C D).sample
puts "Sigint with mode : #{mode}"
case mode
when "A"
puts "A, not exiting"
when "B"
puts "B, not exiting"
when "C"
puts "C, exiting"
exit
else
puts "D, exiting"
exit
end
end
while true
sleep 0.1
p "+1"
end
输出
"+1"
"+1"
^CSigint with mode : A
A, not exiting
"+1"
"+1"
"+1"
"+1"
^CSigint with mode : B
B, not exiting
"+1"
"+1"
"+1"
"+1"
^CSigint with mode : D
D, exiting