Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Script reopens the file in the signal handler

Tags:

file

signals

perl

I have this perl script:

#!/bin/perl
use strict;
use warnings;
use Time::HiRes qw(usleep);
my $fd;
sub reopen {
    open $fd, ">>", "file.log" or die $!;
}
$SIG{USR1} = \&reopen;
reopen();
while(1){
    syswrite $fd, time . " ($$): message\n";
    usleep(100000);
}

I reopen file handle in the signal handler. Is it safe?

like image 268
drlexa Avatar asked Dec 13 '25 08:12

drlexa


1 Answers

Yes[1]. Since 5.8.1, the actual signal handler simply sets a flag saying a signal was received[2]. That flag is checked between statements. System calls (e.g. usleep) return with error $!{EINTR} when interrupted by a signal, allowing the flag to be checked.

The signal will interrupt usleep, and reopen will be called before the next statement (syswrite[3]) is evaluated.


  1. Well, you might want to do local ($!, $^E); in case the interrupted code uses these.
  2. Unless you disable "safe signals".
  3. Why are you using syswrite instead of print? Is it to avoid buffering? Use $fd->autoflush(1); to do that.
like image 102
ikegami Avatar answered Dec 16 '25 01:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!