sliddy
sliddy

Reputation: 135

Handle signals in Perl

How could I write a program which handle such signals ?

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};

Upvotes: 1

Views: 812

Answers (1)

ikegami
ikegami

Reputation: 385556

  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 => $$;

Upvotes: 8

Related Questions