1

When doing fork() using Perl, a child process created and parent process are writing to the same log file, and because of this, the script is getting stuck in windows.

I want child process to write in a different log file, and parent process to write in a different log file so that issue of getting stuck because of two processes writing to the same file at the same time doesn't arise.

Script code snippet:

print "I am parent process";
my $var2=&run_sleep();
print " I am out of subroutine";
print "I want to write in different log file";  


sub run_sleep {                                                                                           
    print "Before fork, parent ID === script ID, i.e $scriptPid \n";
    my $pid = fork(); 
    return $pid if $pid;     # returns to the parent process(out of function) 
    print "Running child process\n";   # Proceeds for the child process
    print "I am child";
    print "PID of child process is $pid\n";
    &function_2();
    &function_3();
    print "I have finished all functions; ending child";

}

Here, I want all the child process's print statements (after the fork) and all the statements(functions) executed by a child should log in a different file, and parent process logs should be in a different log file. [For Windows]

For Linux, I tried the "select" function as follows, and it worked. But, in windows, it's not working.

use feature qw/say/;
use autodie;


# copy STDOUT to another filehandle
open (my $STDOLD, '>&', STDOUT);

# redirect STDOUT to log.txt
open (STDOUT, '>>', 'log.txt');
say 'This should be logged.';

# restore STDOUT
open (STDOUT, '>&', $STDOLD);

say 'This should show in the terminal';
James Z
  • 12,209
  • 10
  • 24
  • 44
AskQuestionsP
  • 153
  • 1
  • 9
  • No idea if it's related or not but you should probably not let the child process return from `run_sleep`. Add `exit(0);` at the end of it. – Ted Lyngmo Jul 14 '21 at 15:05
  • *"my $var2=&run_sleep();"* It is not necessary to put an ampersand in front of the sub name when calling a sub routine, see [perlsub](https://perldoc.perl.org/perlsub) for more information – Håkon Hægland Jul 14 '21 at 16:07
  • *"a child process created and parent process are writing to the same log file"* The code you show does not show any ouput statements to a log file. Please show how the writing to the log file is done. – Håkon Hægland Jul 14 '21 at 16:11
  • Can't get "stuck" for writing to files/file (and you don't say how/where it "gets stuck"). I'd expect the problem to be somewhere else in code, not shown here. – zdim Jul 14 '21 at 18:13

1 Answers1

1

Windows doesn't support forking. The bare bones fork emulation Perl provides creates a thread instead. Since there's only one process, changing STDOUT affects both the "parent" and the "fork". You will need a different approach.

ikegami
  • 367,544
  • 15
  • 269
  • 518