当子进程和父进程在 Perl 中写入同一个日志文件时,进程卡住(在 Windows 中)

时间:2021-07-14 14:57:55

标签: windows perl fork parent-child logfile

在使用 Perl 执行 fork() 时,创建的子进程和父进程正在写入同一个日志文件,因此,脚本会卡在 windows 中。

我希望子进程写入不同的日志文件,而父进程写入不同的日志文件,这样就不会出现由于两个进程同时写入同一个文件而卡住的问题。< /p>

脚本代码片段:

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";

}

这里,我希望子进程的所有打印语句(在fork之后)和子进程执行的所有语句(函数)应该登录到不同的文件中,并且父进程日志应该在不同的日志文件中。 [对于 Windows]

对于Linux,我尝试了如下“选择”功能,并且成功了。但是,在 Windows 中,它不起作用。

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';

1 个答案:

答案 0 :(得分:1)

Windows 不支持分叉。 Perl 提供的裸骨叉仿真创建了一个线程。由于只有一个进程,因此更改 STDOUT 会影响“父”和“叉”。您将需要不同的方法。

相关问题