Method: Signal#trap

Defined in:
signal.c

#trap(signal, command) ⇒ Object (private) #trap(signal) {|| ... } ⇒ Object (private)

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.

Signal.trap(0, proc { puts "Terminating: #{$$}" })
Signal.trap("CLD")  { puts "Child died" }
fork && Process.wait

produces: Terminating: 27461 Child died Terminating: 27460

Overloads:



1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
# File 'signal.c', line 1354

static VALUE
sig_trap(int argc, VALUE *argv, VALUE _)
{
    int sig;
    sighandler_t func;
    VALUE cmd;

    rb_check_arity(argc, 1, 2);

    sig = trap_signm(argv[0]);
    if (reserved_signal_p(sig)) {
        const char *name = signo2signm(sig);
        if (name)
            rb_raise(rb_eArgError, "can't trap reserved signal: SIG%s", name);
        else
            rb_raise(rb_eArgError, "can't trap reserved signal: %d", sig);
    }

    if (argc == 1) {
        cmd = rb_block_proc();
        func = sighandler;
    }
    else {
        cmd = argv[1];
        func = trap_handler(&cmd, sig);
    }

    if (rb_obj_is_proc(cmd) &&
        !rb_ractor_main_p() && !rb_ractor_shareable_p(cmd)) {
        cmd = rb_proc_isolate(cmd);
    }

    return trap(sig, func, cmd);
}