Jasmine Lognnes
Jasmine Lognnes

Reputation: 7087

How to get PID from remote executed command?

If I do the following in Bash, then I get the PID of the remotely started mbuffer, and even though mbuffer is still running, I get the terminal back, which is what I want.

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

Now I would like to do the same in Perl, so I try

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

Here I would have expected that $stdout would have given me the PID from the last echo command, but I got nothing.

Question

How do I get the PID of the remotely executed mbuffer in Perl, and so the Perl script isn't waiting for mbuffer to exit before continuing?

Upvotes: 1

Views: 2689

Answers (1)

Jasmine Lognnes
Jasmine Lognnes

Reputation: 7087

The problem seams to be that it is not possible to execute two commands in one system() or maybe it is, but not possible to get the output from the last command.

Creating a local helper script solved the problem.

#!/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

and in Perl

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

Upvotes: 2

Related Questions