public IRubyObject trap(final IRubyObject recv, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3) {
final JRubySignalHandler handler = new JRubySignalHandler(recv.getRuntime(), arg1, arg2, arg3.toString());
final SignalHandler oldHandler;
try {
oldHandler = Signal.handle(new Signal(handler.signal), handler);
} catch (Exception e) {
throw recv.getRuntime().newArgumentError(e.getMessage());
}
if(oldHandler instanceof JRubySignalHandler) {
return ((JRubySignalHandler)oldHandler).block;
} else {
return RubyProc.newProc(recv.getRuntime(), CallBlock.newCallClosure(recv, (RubyModule)recv,
Arity.noArguments(), new BlockCallback(){
public IRubyObject call(ThreadContext context, IRubyObject[] args, Block block) {
oldHandler.handle(new Signal(handler.signal));
return recv.getRuntime().getNil();
}
}, recv.getRuntime().getCurrentContext()), Block.Type.NORMAL);
}
}