Advertisement
Chessax

Forking in perl 2 (irsssi)

Aug 12th, 2015
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 2.10 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3. #use Irssi;
  4. use vars qw($VERSION %IRSSI);
  5.  
  6. $VERSION = 'PLACEHOLDER';
  7. %IRSSI = (
  8.     authors     => 'PLACEHOLDER',
  9.     contact     => 'PLACEHOLDER',
  10.     name        => 'PLACEHOLDER',
  11.     description => 'PLACEHOLDER',
  12.     license     => '',
  13.     url         => '',
  14.     changed     => 'PLACEHOLDER'
  15.     );
  16.  
  17. my @pids = ();
  18.  
  19. use POSIX ":sys_wait_h"; #WNOHANG
  20.  
  21. #sub dezombify{
  22. #    return !waitpid $_, WNOHANG;
  23. #}
  24.  
  25. sub REAPER{
  26.     my $kid;
  27.     #Reap ALL zombies:
  28.     #QUESTION: Will this interfere with other perl scripts or normal irssi?
  29.     while (($kid = waitpid(-1, &WNOHANG)) > 0){
  30.         ...
  31.     }
  32.     $SIG{CHLD} = \&REAPER;
  33. }
  34.  
  35. sub sig_message_private{
  36.     my ($server, $msg, $nick, $address, $target) = @_;
  37.    
  38.     my $ppid = $$;
  39.    
  40.     #Reap KNOWN zombies:
  41.     #QUESTION: Would this be a better approach?
  42.     ###foreach my $pid (@pids){
  43.     ###    my $status = waitpid $pid, WNOHANG;
  44.     ###    if ($status){
  45.     ###        pop @pids; #Safe to do in foreach?
  46.     ###    }
  47.     ###}
  48.     ##@pids = grep {&dezombify($_)} @pids;
  49.     #@pids = grep { sub{ return !waitpid $_, WNOHANG; }->($_) } @pids;
  50.    
  51.     my $pid = fork();
  52.    
  53.     if (!defined $pid) {
  54.         print 'Unable to fork';
  55.     }
  56.     elsif ($pid == 0){ #Child process
  57.         close(STDOUT);
  58.         close(STDERR);
  59.         my $command = "";
  60.         my @arguments = ();
  61.    
  62.         $command = '/foo/bar';
  63.         @arguments = ('-baz', 'qux');
  64.         unless (-e $command && -x $command){ #Fallback
  65.             $command = '/bin/sleep';
  66.             @arguments = ('2');
  67.         }
  68.        
  69.         exec $command, @arguments;
  70.     }
  71.     else{ #Parent process
  72.         #QUESTION: Should this be done before fork, after fork, or here (in parent)?
  73.         #$SIG{CHLD} = 'IGNORE';
  74.         $SIG{CHLD} = \&REAPER;
  75.        
  76.         #Push child to $pids:
  77.         #if ($kid == -1){
  78.         #    print $prompt_string . 'Unable to wait for ' . $pid;
  79.         #}
  80.         #elsif ($kid == 0){
  81.         #    push @pids, $pid;
  82.         #}
  83.     }
  84. }
  85.  
  86. Irssi::signal_add('message private', 'sig_message_private');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement