3

我想异步运行远程进程并将其远程 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 命令在将远程 pid 回显到 pid_file 后返回,因为没有文件描述符连接到此 ssh 套接字 ( https://unix.stackexchange.com/a/30433/316062 )。

有没有办法以某种方式获取 my_test 退出代码?

4

1 回答 1

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")
于 2019-07-04T07:54:04.850 回答