Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

forked child process is not able to access the file handle

by shammi000 (Novice)
on Jan 27, 2010 at 19:27 UTC ( #820008=perlquestion: print w/replies, xml ) Need Help??
shammi000 has asked for the wisdom of the Perl Monks concerning the following question:

Hi All, I am writing a daemon to kill all slow queries. My daemon code is shown below.
sub Daemonize() { my $pid; $pid=fork(); if(! defined($pid) ){ #Forking Failed, we exit at this point die("forking failed\n"); exit(1); } if ($pid>0) { print LOG "Forking Success. Child PID: $pid \n"; exit(); } $|=1; print LOG "Child Process Executing... \n"; setsid(); chdir('/'); umask(0); close(STDIN) ; close(STDOUT) ; close(STDERR) ; }
I have opened the file handle LOG before calling daemonize and, after the deamonize, i have one more function to do the slow query kill. I am not able to view any of the log messages i am writing from the child process in LOG. also query killing is not happening. I can see the child pid running when checked with ps. Please help me. Shammi

Replies are listed 'Best First'.
Re: forked child process is not able to access the file handle
by chromatic (Archbishop) on Jan 27, 2010 at 21:39 UTC

    If you want your logging filehandle to avoid buffering, you have to disable it explicitly for that handle, not STDOUT (as you're doing now). I prefer the IO::Handle approach and lexical filehandles to select/$| mangling:

    use IO::Handle; sub daemonize { my $log = shift; $log->autoflush( 1 ); # forking code goes here if ($pid > 0) { print {$log} "Forking Success. Child PID: $pid \n"; exit(); } print {$log} "Child Process Executing... \n"; setsid(); # ... }

    Of course, if you've gone that far, it's not too far to use some sort of logging object that takes care of buffering/unbuffering and newlines for you, but that's more work than you suggested you need right now.

Re: forked child process is not able to access the file handle
by Krambambuli (Curate) on Jan 27, 2010 at 21:57 UTC
    If I'm seeing it right, you're exiting the parent process too soon - and the log file is closed before the childs get a chance to write into it.

    Try to outcomment the parent exit(), just to see if this diagnosis is correct.

    If it is, consider keeping the parent alive till the last child finished it's work.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://820008]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (11)
As of 2017-01-19 13:31 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (170 votes). Check out past polls.