how to kill process having multiple fork using perl

前端 未结 1 1261
时光取名叫无心
时光取名叫无心 2021-01-23 06:21

I have a test-case where multiple fork is used to create grandchild and the parent process is in infinite loop, I am implementing a perl script to kill the process. Currently it

1条回答
  •  醉梦人生
    2021-01-23 06:52

    In a more complicated case, you can set the perl child process to be a session leader with POSIX::setsid(), and then send the signal to the process group by passing a negative value to kill.

    if(!defined( my $pid = fork())) {
        die "Cannot fork a child: $!";
    } elsif ($pid == 0) {
        POSIX::setsid();        # make this process a session leader
        print "Printed by child process\n";
        system("./program_that_forks"); exit;  #  or exec('./program_that_forks')
    
    } else {
        ...
        kill('KILL', -$pid);    #  -$pid means signal the whole process group
        ...
    }
    

    If the program_that_forks is also manipulating process groups, either by calling setsid(1) or by closing standard file descriptors and becoming a daemon, the convention is for the program to write its process id to a file, and for system task scripts to read this file to signal the program (run ls /var/run/*.pid to see some examples).

    0 讨论(0)
提交回复
热议问题