Perl中异步执行子进程并捕获输出的问题求助
解决Perl异步执行命令并收集输出的问题
你的代码没有输出的核心原因是:Perl线程默认不会共享非全局变量,子线程里的$out1、$out2是主线程变量的副本,线程内的修改不会同步到主线程。下面提供两种可行的修复方案:
方案1:使用共享变量
通过threads::shared模块将变量声明为线程共享,让子线程和主线程操作同一个变量:
#!/usr/bin/env perl use warnings; use strict; use threads; use threads::shared; use IPC::Run3; my $out1 :shared = ""; my $t1 = async { run3([qw(echo foo)], \undef, \$out1, \undef); }; my $out2 :shared = ""; my $t2 = async { run3([qw(echo bar)], \undef, \$out2, \undef); }; my $out3 = ""; run3([qw(echo bar)], \undef, \$out3, \undef); $t1->join(); $t2->join(); print("$out1\n"); print("$out2\n"); print("$out3\n");
方案2:让线程返回输出结果
更简洁安全的方式是让子线程直接捕获命令输出并返回,主线程通过join()获取结果,避免共享变量的潜在问题:
#!/usr/bin/env perl use warnings; use strict; use threads; use IPC::Run3; my $t1 = async { my $output; run3([qw(echo foo)], \undef, \$output, \undef); return $output; }; my $t2 = async { my $output; run3([qw(echo bar)], \undef, \$output, \undef); return $output; }; my $out3 = ""; run3([qw(echo bar)], \undef, \$out3, \undef); my $out1 = $t1->join(); my $out2 = $t2->join(); print("$out1\n"); print("$out2\n"); print("$out3\n");
两种方案都能正常输出:
foo bar bar
内容的提问来源于stack exchange,提问作者Philippe
相关产品推荐
相关产品推荐

