Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

Comment on forked child process is not able to access the file handle
Download Code
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 (Deacon) 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.


    Krambambuli
    ---

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://820008]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2014-09-18 22:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (126 votes), past polls