Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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
[choroba]: Email::Address DoS

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2018-06-20 11:54 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (116 votes). Check out past polls.