Perl forward SIGINT to parent process from `system` command

前端 未结 1 895
时光取名叫无心
时光取名叫无心 2021-01-19 00:56

If I have a long-running system command like apt-cache search , is there a way to forward a SIGINT sent via ^C

相关标签:
1条回答
  • 2021-01-19 01:42

    Make the child the head of a process group, then send the signal to the whole process group.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use autodie;
    
    use POSIX qw( setpgid );
    
    my $child_pid;
    
    $SIG{INT} = sub {
        kill INT => -$child_pid if $child_pid;
        exit(0x80 | 2);  # 2 = SIGINT
    };
    
    my $child_pid = fork();
    if (!$child_pid) {
        setpgid($$);
        exec 'apt-cache', 'search', 'hi';
    }
    
    WAIT: {
       no autodie;
       waitpid($child_pid, 0);
       redo WAIT if $? == -1 and $!{EINTR};
       die $! if $? == -1;
    }
    
    exit( ( $? >> 8 ) | ( 0x80 | ( $? & 0x7F ) ) );
    
    0 讨论(0)
提交回复
热议问题