Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which line of code was being executed when a signal is received

Tags:

perl

interrupt

I'm trying to do something like this

$SIG{ALRM} = sub {
    print $line_number_when_alarm_went_off;
};

alarm 10;

# rest of the script

I'm using ALRM as an example, I will end up using a different signal to kill from the outside to trigger it. Is there a neat way of doing this sort of operation?

I have some slow scripts and sometimes I would like to send them a signal to know where the code is at that moment.

I want to make this as unobtrusive as possible so I could package it and add it to legacy code.

like image 721
Nullman Avatar asked Feb 09 '17 15:02

Nullman


1 Answers

You can use caller in list context to get the package, file and line number of the place that the current sub got called from.

$SIG{ALRM} = sub {
    my ($pkg, $file, $line) = caller;

    CORE::say $line;
    die;
};

alarm 2;

while (1) {
    1;
}

This will output 11 (if I counted correctly, in my file it's 1740, and the $SIG line is 1730.

It also works with other signal handlers, like warn.

$SIG{__WARN__} = sub {
    my ($pkg, $file, $line) = caller;

    CORE::say $line;
};

warn 'foo';

This will output 7

Note that your code has a syntax error. You are assigning a hash reference as a signal handler, not a sub reference!

like image 187
simbabque Avatar answered Oct 12 '22 15:10

simbabque