in reply to Deamon: Need Child to exit if parent dies

See kill and getppid. Here's a recipe:

#!/usr/bin/perl print "process $$ started\n"; if ((my $pid = fork) == 0) { my $ppid = getppid; while (1) { sleep 1; unless (kill 0, $ppid) { print "child: parent($ppid) gone, exiting.\n"; exit; } else { print "child: parent($ppid) still alive...\n"; } } } else { my $secs = int rand 20; print "parent: sleeping $secs seconds\n"; sleep $secs; } print "parent: exiting after 1 second\n"; sleep 1;

Replies are listed 'Best First'.
Re^2: Daemon: Need Child to exit if parent dies
by JavaFan (Canon) on Jan 05, 2010 at 11:43 UTC
    That may not work correctly. The parent may exit, and its PID reused before the child gets a change to check, or either process may have changed UID (which is not uncommon for daemons) - the kill 0 will then fail, but all kill 0 tells you is whether the current process can send a signal to the other one - not existence is only one reason why a signal cannot be send.