我该如何重新抛出SIGINT?

时间:2017-01-16 14:28:34

标签: ruby signals

我现在有什么:

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

1 个答案:

答案 0 :(得分:1)

请按照@ndn的建议来定义trapcase内的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