【问题标题】:Execute a script through ssh and store its pid in a file on the remote machine [duplicate]通过ssh执行脚本并将其pid存储在远程机器上的文件中[重复]
【发布时间】:2019-10-20 02:54:29
【问题描述】:

通过 ssh 在后台运行脚本时,我无法在远程计算机上的文件中存储任何 PID

我需要将脚本进程的PID 存储在一个文件中,以便在需要时将其终止。在它正在工作的远程机器上运行确切的命令时,为什么通过 ssh 它不能正常工作?

以下命令有什么问题:

ssh user@remote_machine "nohup ./script.sh > /dev/null 2>&1 & echo $! > ./pid.log"

结果:文件pid.log 已创建但为空。

预期:文件pid.log 应该包含运行脚本的PID

【问题讨论】:

标签: bash ssh pid nohup


【解决方案1】:

使用

ssh user@remote_machine 'nohup ./script.sh > /dev/null 2>&1 & echo $! > ./pid.log'

ssh user@remote_machine "nohup ./script.sh > /dev/null 2>&1 & echo \$! > ./pid.log"

问题: Your $! was getting expanded locally, before calling ssh at all.

更糟糕的是,在调用 ssh 命令之前,如果有一个进程在后台盯着看,那么 $! 将扩展为该进程,并且完整的 ssh 命令将扩展为包含该 PID 作为 echo 的参数。

例如

$ ls &
[12342] <~~~~ This is the PID of ls
$ <~~~~ Prompt returns immediately because ls was stared in background. 
myfile1 myfile2 <~~~~ Output of ls.
[1]+  Done                    ls
#### At this point, $! contains 12342
$ ssh user@remote "command & echo $! > pidfile"
# before even calling ssh, shell internally expands it to:
$ ssh user@remote "command & echo 12342 > pidfile"

它会在pidfile中放入错误的PID。

【讨论】:

  • 谢谢@anishsane!那确实是我的问题:)
猜你喜欢
  • 1970-01-01
  • 2011-08-05
  • 2012-09-30
  • 2011-05-09
  • 2014-01-20
  • 2012-01-12
  • 2021-06-13
  • 2016-11-05
  • 1970-01-01
相关资源
最近更新 更多