Gorby has asked for the wisdom of the Perl Monks concerning the following question:

I have a program, written in perl of course, that uses "fork". I would like to be able to kill off the parent and the child created by "fork" at some point within the program without terminating the whole program itself. How can I do this? Please help? Thanks very much.

Replies are listed 'Best First'.
Re: Killing Parents and Children
by tachyon (Chancellor) on Feb 26, 2003 at 10:21 UTC

    When a program forks the fork returns the pid of the child so the parent can use this to kill it at will.

    my $pid = fork(); if ( $pid == 0 ) { # child process so do stuff here # usually have an exit to ensure child # does not escape this if clause exit; } else { # parent process, waits a while sleep 60 # kills child kill 9, $pid; } # parent continues on here (as will child if not killed or exited)

    You seem somewhat confused about forking. The parent is the whole program. It spawns children and continues. The child is a whole copy of the program and gets copies of all the data/handles to that point.

    There is a vast quantity of discussion about fork on PM - you can find it using Super Search

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: Killing Parents and Children
by robartes (Priest) on Feb 26, 2003 at 10:23 UTC
    Hmm, there is no way of killing both parent and children without 'killing the program itself'. In fact, once you fork, there are multiple instances of the program itself running.

    If you want to kill off children after a certain time, simply make use of the child PID returned by fork:

    #!/usr/local/bin/perl -w use strict; my @child; for (0..5) { print "Spawning child $_\n"; $child[$_]=spawn(sub {while (1) {}}); } sleep 5; for (0..5) { print "Killing child $_\n"; kill 15, $child[$_]; } sub spawn { my $code=shift; #die "Something fishy - could not fork\n" if ((my $pid = fork())== - +1); # Oops - wrong fork() semantics die "Something fishy - could not fork\n" unless (defined(my $pid=for +k())); return $pid if ($pid); exit &$code; }

    Update: I was stuck in C - see comments in code :)

    CU
    Robartes-

Re: Killing Parents and Children
by mowgli (Friar) on Feb 26, 2003 at 11:57 UTC

    Assuming you have only forked once, there is no way to keep the program running while killing both the parent and the child process. In fact, I am not really sure what you mean exactly when you refer to "the whole program itself"; the program, when running, consists merely of the parent process and its children (with associated data etc. of course)

    Maybe you could post a clarification to explain what exactly you want to do? Also, posting your program (or part of it) might help, if that's possible.

    --
    mowgli