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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.