Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting STDOUT in child process

Tags:

perl

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
like image 755
Arav Avatar asked Nov 01 '12 05:11

Arav


2 Answers

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:

The Problem is child process STDOUT gets redirected into the parent log file as well as the child log file.

This because when you open file with pipe (open(STDOUT, "|tee ...) as a underlying result your process fork() to create child process and then exec into program what you run (tee). Forking(for tee) takes STDOUT of master process so tee will write into parent's logfile. So i think you must revoke using STDOUT handle for master process. Or, second way - remove use of tee - its simplest way.

Also i dont understand in the below setEnvironment function the purpose of creating OUT and ERR file handle.

Seems this is someone's woraround about problem above. You can grep -rE ' \bERR\b' . to search in code if it used or not. Probably someone wanted to save real STDOUT and STDERR to further use.

like image 134
PSIAlt Avatar answered Oct 13 '22 01:10

PSIAlt


It would appear that the intent of the original code is as follows:

  1. when the script is started from, say, a terminal, then provide aggregate parent and child output to the terminal
  2. additionally, provide a copy of the parent output in parent.log, and a copy of child output in child.log

Note that @Unk's answer is correct as far as 2. goes, and has less moving parts than any code using tee, but fails to achieve 1.

If it is important to achieve both 1. and 2. above, then take your original code and simply add the following at the top of your setEnvironment method:

sub setEnvironment()
{
    if ( fileno OUT )
    {
        unless ( open(STDOUT, ">&OUT") )
        {
            print "Cannot restore STDOUT";
            return 2;
        }
        unless ( open(STDERR, ">&ERR") )
        {
            print "Cannot restore STDERR";
            return 2;
        }
    }
    else
    {
        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") )
    ...

Incidentally, do not forget to also add $pid to @pids if your actual code does not do that already:

  ...
  my $pid = fork;
  if ( $pid ) {
      push @pids, $pid;
      ...

Why and how does this work? We simply want to temporarily restore the original STDOUT immediately before rewiring it into tee, so that tee inherits it as its standard output and actually writes directly to the original STDOUT (e.g. your terminal) instead of writing (in the case of the forked children) through the parent's tee (which is where the child's STDOUT normally pointed to before this change, by virtue of inheriting from the paremnt process, and which is what injected those child lines into parent.log.)

So in answer to one of your questions, whoever wrote the code to set OUT and ERR must have had exactly the above in mind. (I cannot help but wonder whether or not the difference in indentation in your original code is indicative of someone having removed, in the past, code similar to the one you have to add back now.)

Here's what you now get at the end of the day:

$ rm -f parent.log child.log
$ perl test.pl
child
parent
child
parent
parent
child
parent
child
parent
$ cat parent.log
parent
parent
parent
parent
parent
$ cat child.log
child
child
child
child
child
like image 41
vladr Avatar answered Oct 13 '22 01:10

vladr