如何将两个命令输出的输出并行发送到标准输出?

时间:2013-12-28 17:56:14

标签: linux perl unix

我想使用xinput来监视击键次数和鼠标移动次数。为了简化,让我们说出我想要的是这两个命令:

xinput test 0
xinput test 1

同时写入屏幕。

我在Perl脚本中使用它,如:

open(my $fh, '-|', 'xinput test 0') or die $!;
while(my $line = <$fh>) {
...stuff to keep count instead of logging directly to file
}

编辑: 类似的东西:

open(my $fh, '-|', 'xinput test 0 & xinput test 1') or die $!;

不起作用。

2 个答案:

答案 0 :(得分:2)

我不确定你想要对输出做什么,但听起来你想同时运行这些命令。在这种情况下,我的第一个想法是每个命令分叉一次Perl进程,然后将子进程执行到你关心的命令。

foreach my $command ( @commands ) {  # filter @commands for taint, etc
    if( fork ) { ... } #parent
    else { # child
        exec $command or die "Could not exec [$command]! $!";
        }
    }

分叉进程共享相同的标准文件句柄。如果您需要父进程中的数据,则必须在两者之间建立某种通信。

CPAN上还有几个用于处理异步多进程内容的Perl框架,例如POEAnyEvent等。他们会为您处理所有这些细节。

答案 1 :(得分:0)

如果您想同时在控制台上同时编写这两个命令,只需在后台运行它们:

xinput test 0 &
xinput test 1 &

但首先你必须确保将控制台设置为允许的方案,否则后台进程将在尝试在控制台上写入时停止。此代码将关闭stty tostop选项:

stty -tostop