How can I timeout a forked process that might hang?

后端 未结 4 568
走了就别回头了
走了就别回头了 2021-02-09 08:36

I am writing a Perl script that will write some inputs and send those inputs to an external program. There is a small but non-zero chance that this program will hang, and I want

4条回答
  •  旧时难觅i
    2021-02-09 09:26

    I was able to successfully kill my exec()ed process by killing the process group, as shown as the answer to question In perl, killing child and its children when child was created using open. I modified my code as follows:

    my $pid = fork;
    if ($pid > 0){
        eval{
            local $SIG{ALRM} = sub {kill 9, -$PID; die "TIMEOUT!"};
            alarm $num_secs_to_timeout;
            waitpid($pid, 0);
            alarm 0;
        };
    }
    elsif ($pid == 0){
        setpgrp(0,0);
        exec('echo blahblah | program_of_interest');
        exit(0);
    }
    

    After timeout, program_of_interest is successfully killed.

提交回复
热议问题