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.
man signal
有详细说明
trap(2){ ... }
, trap('INT'){}
, trap('SIGINT'){ ... }
是一样的,ctrl + c 就调用 block 了
@bhuztez 信号量是 Unix 搞出来的吧 win 又不需要必须遵循 Posix 标准 不过 win 有 Posix 子系统 默认不安装但是 而且 win8 以后就被废弃
若将系统中尚未定义的信号指定给 trap 时,会引发 ArgumentError 异常。例如,在本地 Windows 系统 (mswin32, mingw 等) 上的 ruby 环境中,则只定义了INT ILL FPE SEGV TERM BREAK ABRT EXIT. 这里
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 信号。"