新手问题 请问 trap 是如何使用的?能给个简单的例子最好了!

wzhang1987 · 2013年01月15日 · 最后由 wwwicbd 回复于 2017年09月01日 · 7313 次阅读

x = “AA”

puts x

trap ("AA") {puts "get"} x.trap ("AA") {puts "get"}

#以上 2 种方式都不行,提示 unsupported signal SIGAA (ArgumentError) 请教各位大侠如何使用 trap?

@wzhang1987 没用过 trap 也没怎么处理过 signal,不过文档里面看了下 trap 就是给中断信号添加回调,很显然你的 SIGAA 根本是个未定义的信号
这里有篇博文将的 linux 的信号处理机制,不知道楼主是不是都了解过了 :http://www.cnblogs.com/taobataoma/archive/2007/08/30/875743.html
这是 ruby 文档的 copy: Specifies the handling of signals. The first parameter is a signal name (a string such as “SIGALRM”, “SIGUSR1”, and so on) or a signal number. The characters “SIG” may be omitted from the signal name. The command or block specifies code to be run when the signal is raised. If the command is the string “IGNORE” or “SIG_IGN”, the signal will be ignored. If the command is “DEFAULT” or “SIG_DFL”, the Ruby’s default handler will be invoked. If the command is “EXIT”, the script will be terminated by the signal. If the command is “SYSTEM_DEFAULT”, the operating system’s default handler will be invoked. Otherwise, the given command or block will be run. The special signal name “EXIT” or signal number zero will be invoked just prior to program termination. trap returns the previous handler for the given signal.

@sailtsao ruby 那个看是看过的,看不太懂。。 不清楚 trap 是怎么识别信号的,我回去看看你的链接,谢谢。

kill -l man kill

man signal 有详细说明

trap(2){ ... }, trap('INT'){}, trap('SIGINT'){ ... } 是一样的,ctrl + c 就调用 block 了

另外 windows 的话基本不支持信号,ruby 里用 Signal.list 可以看哪些是 ruby 可以用的

#5 楼 @luikore 。。。 windows 不能用吗。。。。

#6 楼 @wzhang1987 windows 是完全不符合标准的操作系统,应该会支持 sigexit 和 sigint, 不过也是模拟出来的...

#7 楼 @luikore 你这是歧视 Windows 啊...

@bhuztez 信号量是 Unix 搞出来的吧 win 又不需要必须遵循 Posix 标准 不过 win 有 Posix 子系统 默认不安装但是 而且 win8 以后就被废弃

若将系统中尚未定义的信号指定给 trap 时,会引发 ArgumentError 异常。例如,在本地 Windows 系统 (mswin32, mingw 等) 上的 ruby 环境中,则只定义了INT ILL FPE SEGV TERM BREAK ABRT EXIT. 这里

Linux 信号说明

main.rb

puts Process.pid

trap(:SIGUSR1) do
  puts "收到 USER1 信号."
end

sleep

terminal1

$ ruby -v main.rb 
ruby 2.3.4p301 (2017-03-30 revision 58214) [x86_64-darwin16]
1146

terminal2

$ ruby -ve "Process.kill(:SIGUSR1, 1146)"

然后 terminal1 就会打印 "收到 USER1 信号。"

需要 登录 后方可回复, 如果你还没有账号请 注册新账号