Hello monks, any help with a vexing issue I am having would be appreciated. I'm trying to write a program that will basically act as a daemon (no networking component, just run continuously disconnected from a shell). I'm not too familiar with forking though nor have I ever written anything like this in any other language. So I decided to write a short program to work out this issues I've been having with it but I can't get that to do what I want either. I'm using perl 5.10.1. The logic I am using to create the daemon is as follows: !) Fork 2) close the parent 3) fork the child 4) close the child and run your code in the grandchild Here is the code I'm having trouble with:
#!/usr/bin/env perl use strict; my $pid = fork(); if ($pid == 0){ # child print "Testing daemon\n"; my $child = fork(); if ($child == 0) { # grandchild open TEST, ">", "$ENV{HOME}/daemon.test" or exit 2; my $i = 0; while ($i < 10){ print TEST "Alive\n"; sleep 5; } close TEST; exit 0; } print "Exiting child\n"; print "Grandchild PID is $child\n"; exit 0; } # parent print "Parent process is $$: Child is $pid\n"; print "Exiting Parent\n"; exit 0;
So everything runs fine until it gets to the grandchild. For some reason it doesn't seem to be doing anything after opening the filehandle (I'm used to checking for filehandle open errors with die but I wasn't sure what would happen if a message from a grandchild process no longer connected to a parent or grandparent got printed to STDERR. Anyway, the message never gets printed to the daemon.test file nor does the grandchild ever exit. What am I missing?
In reply to Problems with forking by mraspberry
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |