我目前所拥有的:
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发布于 2017-01-17 01:26:44
请
请遵循@ndn的建议在case或if中定义trap,而不是相反。
取消定义trap
注意:这只是一个概念证明!
在when "C"内部调用Process.kill('INT', Process.pid)只会再次在trap中被捕获。您需要先取消定义trap。在documentation中:
如果命令为“default”或“SIG_DFL”,则将调用
的默认处理程序。
下面是一个例子:
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:
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, exitinghttps://stackoverflow.com/questions/41678653
复制相似问题