All other answers are correct (in particular, PSIalt). I just hope I can answer with a revised code that exactly matches this question. Key factors to note:
"| tee -ai ..."
Tee commands print their standard in the standard order, and also print to this file. As PSIalt says, deleting is the easiest way to ensure that each process only outputs the correct file.
setEnvironment () inside the loop for the parent
The source code constantly redirects STDOUT back to the tee ed file. Therefore return STDOUT. Given my code below, if you moved setEnvironment to the above #parent process code goes here , you will see all but one of “Real STDOUT” and “Real STDERR” that actually appear in parent.log.
Functions
Ideal is to remove any STDOUT / STDERR redirect dependency for logging. I will have a dedicated log($level, $msg) function log($level, $msg) and start moving all the code to use it. Initially, this is normal if it’s just a façade for existing behavior - you can just turn it off when you reach the appropriate threshold for the code that is covered.
If this is a basic script and doesn't produce stupidly large logs, why not just print everything in STDOUT with some kind of prefix that you can grep for (for example, "PARENT: '/' CHILD: ')?
This is a bit out of the question, but consider using a more structured approach to logging. I would consider using a CPAN registration module, for example. Log :: Log4perl . Thus, the parent and children can simply request the correct category of magazines, and not interfere with the work with files. Additional benefits:
- Standardize output
- Allow reconfiguration on the fly - change the logging level from ERROR to DEBUG on a running system with an error
- It is easy to redirect output - you do not need to change the code to reorder log files, rotate files, redirect to socket / database, etc.
use strict; use warnings; our $g_LOGPATH = '.'; our $g_LOGFILE = "parent.log"; our @pids; setEnvironment(); for ( 1 .. 5 ) { my $pid = fork; if ($pid) {
child.log:
child child child child child
parent.log:
parent parent parent parent parent
STDOUT taken from the terminal:
Real STDOUT (x5 lines)
STDERR taken from terminal:
Real STDERR (x5 lines)