Search code examples
perlsignals

Handle signals in Perl


How could I write a program which handle such signals ?

  • SIGUSR1 - Print the statistic (like the dd utility does);
  • SIGUSR2 - Print the amount of free memory;
  • SIGINT - Send USR1 to itself and quit the program.

This is what I have and there is no output:

$| = 1;
kill 'USR1';
kill 'USR2';

$SIG{USR1} = {print `dd if=/def/zero of=/dev/null bs=512`};
$SIG{USR2} = {print `free -m`};
$SIG{INT}  = {kill 'USR1' => $$; die};

Solution

    1. You didn't specify to which program you wanted to send the signal.
    2. You sent the signals before setting the handlers!
    3. You're missing "sub".

    use strict;
    use warnings;
    
    $| = 1;
    
    $SIG{USR1} = sub { print `dd if=/def/zero of=/dev/null bs=512`; };
    $SIG{USR2} = sub { print `free -m`; };
    $SIG{INT}  = sub { kill USR1 => $$; die "Interrupt"; };
    
    kill USR1 => $$;
    kill USR2 => $$;
    

    Also,

    1. print `...` is a silly way of writing system('...').
    2. Don't send a signal to call a function!

    use strict;
    use warnings;
    
    $| = 1;
    
    sub job1 { system('dd if=/def/zero of=/dev/null bs=512'); }
    sub job2 { system('free -m'); }
    
    $SIG{USR1} = \&job1;
    $SIG{USR2} = \&job2;
    $SIG{INT}  = sub { job1(); die "Interrupt"; };
    
    kill USR1 => $$;
    kill USR2 => $$;