Have a Parent process which spawns multipe child process via fork. I want the log files by the parent and child process to be separate. The Problem is child process STDOUT gets redirected into the parent log file as well as the child log file. Not sure what i need to change to avoid child process log message to get into the parent log file. Also i dont understand in the below setEnvironment function the purpose of creating OUT and ERR file handle. This is a existing code so i kept as it is. In the parent process and child process i set the variable $g_LOGFILE to contain different file name so that separate log files are created. Also i call setEnvironment function in both parent and child process. I tried by closing STDOUT,STDERR,STDIN in the child process and calling the setenvironment but it was not working properly.
sub setEnvironment()
{
unless ( open(OUT, ">&STDOUT") )
{
print "Cannot redirect STDOUT";
return 2;
}
unless ( open(ERR, ">&STDERR") )
{
print "Cannot redirect STDERR";
return 2;
}
unless ( open(STDOUT, "|tee -ai $g_LOGPATH/$g_LOGFILE") )
{
print "Cannot open log file $g_LOGPATH/$g_LOGFILE");
return 2;
}
unless ( open(STDERR, ">&STDOUT") )
{
print "Cannot redirect STDERR");
return 2 ;
}
STDOUT->autoflush(1);
}
####################### Main Program ######################################
$g_LOGFILE="parent.log";
while ($file = readdir(DIR))
{
my $pid = fork;
if ( $pid ) {
setEnvironment();
#parent process code goes here
printf "%s\n", "parent";
next;
}
$g_LOGFILE="child.log";
setEnvironment();
#child code goes here
printf "%s\n", "child";
exit;
}
wait for @pids
Ok i tested this code alitle. Here is my sample code. In my code there is similar(not exact) problem: all messages are double-written to childs log file.
So my answers to your questions:
This because when you open file with pipe (
open(STDOUT, "|tee ...) as a underlying result your processfork()to create child process and thenexecinto program what you run (tee). Forking(for tee) takes STDOUT of master process soteewill write into parent’s logfile. So i think you must revoke using STDOUT handle for master process. Or, second way – remove use oftee– its simplest way.Seems this is someone’s woraround about problem above. You can
grep -rE 'to search in code if it used or not. Probably someone wanted to save real STDOUT and STDERR to further use.\bERR\b' .