如何从远程执行命令中获取PID?

时间:2014-08-02 20:04:43

标签: linux bash perl ssh

如果我在Bash中执行以下操作,那么我将获得远程启动的mbuffer的PID,即使mbuffer仍在运行,我也会将终端返回,这就是我想要的。

read -r pid < <(ssh 10.10.10.47 'nohup /opt/omni/bin/mbuffer -4 -s 128k -m 2G -v 0 -q -I 8023 >/tmp/mtest </dev/null 2>/tmp/mtest.err & echo $!')

echo $pid

现在我想在Perl中做同样的事情,所以我尝试

use Capture::Tiny 'capture';

my ($stdout, $stderr, $exit) = capture {
    system("read -r pid < <(ssh 10.10.10.47 'nohup /opt/omni/bin/mbuffer -4 -s 128k -m 2G -v 0 -q -I 8023 >/tmp/mtest </dev/null 2>/tmp/mtest.err & echo $!'); echo \$pid");
};

print "stdout $stdout\n";
print "stderr $stderr\n";
print "exit   $exit\n";

在这里,我原以为$stdout会从最后一个echo命令给我PID,但我什么也没得到。

问题

如何在Perl中获取远程执行的mbuffer的PID,因此Perl脚本在继续之前不等待mbuffer退出?

1 个答案:

答案 0 :(得分:2)

问题是不可能在一个system()中执行两个命令,或者可能是,但是不可能从最后一个命令获得输出。

创建本地帮助程序脚本解决了这个问题。

#!/usr/bin/bash

# Redirection of stdin and stderr to files (preventing them from holding
# handles that connect, eventually, to the terminal).

read -r pid < <(ssh $1 "/usr/gnu/bin/nohup /opt/omni/bin/mbuffer -4 -s 128k -m 2G -v 0 -q -I 8023 >/tmp/mtest$2 </dev/null 2>/tmp/mtest.err & echo \$!")

echo $pid

和Perl

my ($stdout, $stderr, $exit) = capture {
     system("/comp/mbuffer-zfs-listen.sh 10.10.10.47 11");
};