Advertisement

[Perl+Linux] Check in child process wether parent process still exists or not

Started by July 12, 2005 10:42 AM
11 comments, last by GameDev.net 19 years, 3 months ago
I need to know how I can find out wether the parent of a child still exists. Does anyone know how? Pwetty pwease?
You can check the pid of the parent, with getppid().
If the returned pid is equal to 1 (the init process) then
the parent has died.

like this:
#!/usr/bin/perl -wif (fork() == 0) {	print "1: ",getppid(),"\n";	sleep(2);	print "2: ",getppid(),"\n";}
Advertisement
^^ But isn't that only possible when I do the fork? What I want to do is check for the parent process AFTER I've forked, this can be 1 minute after forking or 1 hour or more if I want to.

BTW, I already know the parent PID in the child processes. I put it in a variable at the beginning of my script.
You can do this check where and whenever you like, it will still work. And it doesn't matter that you know the pid of the parent, since when the parent dies, so does the pid.

That's why you're checking if the pid of the parent is 1 (with getppid()). PID 1, is the init process on linux. All children who gets orphaned get the init process as a parent.

so:

sub is_parent_dead() {  if (getppid() == 1) {    return 1; # yes  }  return 0; # no}


/Nico
Thanks. I'll try that when I go to work again... I have 2 weeks vacation now so I gotta wait a while.
Nope, it doesn't work. The 'is_parent_alive' always returns 0 no matter if the parent is alive or not.
Advertisement
so this:

if (fork() == 0) {	while (is_parent_dead() == 0) { ; }	print "My parent just died!\n";	exit(0);}sleep(2);print "dying..\n";sub is_parent_dead() {  if (getppid() == 1) {    return 1; # yes  }  return 0; # no}


doesn't print, "dying.." (after 2 seconds) then "My parent just died!"?
Nope. Instead I got a message

main::is_parent_dead() called too early to check prototype at test.pl line 7.
dying..

The parent proces died but the child proces was left behind searching it's parent at full CPU speed... so I had to kill the poor child myself.


Well, you might need to add a forward declaretion.
Just add 'sub is_parent_dead();' at the top.

#!/usr/bin/perl -wsub is_parent_dead();if (fork() == 0) {  while (is_parent_dead() == 0) { ; }  print "My parent just died!\n";  exit(0);}sleep(2);print "dying..\n";sub is_parent_dead() {  if (getppid() == 1) {    return 1; # yes  }  return 0; # no}


If that doesn't work.. I don't know what will :)
Doesn't work either. The forward declaration gives this message

"Prototype mismatch: sub main::is_parent_dead () vs none"


And the child proces still hangs thinking its parent is still alive. :(
Thanks for helping anyway. I'll give this thing a brake and find another solution some other time.

This topic is closed to new replies.

Advertisement