Saturday, October 15, 2011

Signal in perl multi-processes

Catch a signal in Perl is easy.

   
  # main 
  $PID = $$; 
  $SIG{'INT'} = "final_cleanup";

  my $pid = fork();

  if (!defined($pid)) {
      print "Error in fork: $!";
      exit 1;
  }
  ...

  sub final_cleanup {
    ...
  } 
 
But I found every sub processes run final_cleanup. It is not what I want
- run it in main only. Others just exit. Below is the revised version:
 
  # main 
  $PID = $$; 
  $SIG{'INT'} = "INT_exit";
  
  my $pid = fork();

  if (!defined($pid)) {
      print "Error in fork: $!";
      exit 1;
  }

  ...

  sub final_cleanup {
    ...
  }  
  sub INT_exit {
 
    if ( $PID == $$ ) {
      sleep 3;
      print "MAIN PID $$ == Please wait to collect all subprocesses ...\n";
      final_cleanup();
    }
    else {
      print "PID $$ existing ...\n";
    }
    exit(0);

  }

No comments:

Post a Comment