在bash上异步运行远程进程,并在文件中获取其远程pid,stdout + stderr并退出代码

时间:2019-07-03 08:29:16

标签: bash ssh exit-code remote-process

我想异步运行一个远程进程,并将其远程pid,输出(stdout + stderr)保存到文件或变量(我需要它进行进一步处理)中并退出代码。

运行远程进程时需要远程pid,而不是在完成之后。 另外,具有相同名称的多个进程将在远程计算机上运行,​​因此使用该进程名称的任何解决方案都将不适用于我。

到目前为止我所拥有的:

export SSH="ssh -o ServerAliveInterval=100 $user@$remote_ip"

“ my_test”是我要运行的二进制文件。

要获取远程pid和输出,我尝试过:

$SSH "./my_test > my_test_output & echo \$! > pid_file"
remote_pid=$($SSH "cat pid_file")
# run some remote application which needs the remote pid (send signals to my_test)
$SSH "./some_tester $remote_pid"
# now wait for my_test to end and get its exit code
$SSH "wait $remote_pid; echo $?"
bash: wait: pid 71033 is not a child of this shell

由于没有ssh套接字(https://unix.stackexchange.com/a/30433/316062)连接到文件描述符,因此$ SSH命令在将远程pid回显到pid_file之后返回。

是否可以通过某种方式获取my_test退出代码?

1 个答案:

答案 0 :(得分:0)

好的,我的解决方法是:

    # the part which generates the code on the remote machine
    $SSH << 'EOF' &
    ./my_test > my_test_output &
    remote_pid=$!
    echo $remote_pid > pid_file
    wait $remote_pid
    echo $? > exit_code
    EOF
    local_pid=$!

    # since we run the previous ssh command asynchronically, we need to make sure
    # pid_file was already created when we try to read it
    sleep 2
    remote_pid=$($SSH "cat pid_file")
    # now we can run remote task which needs the remote test pid
    $SSH "./some_tester $remote_pid"
    wait $local_pid
    echo "my_test is done!"
    exit_code=$($SSH "cat exit_code")