【发布时间】:2015-11-29 18:59:23
【问题描述】:
我最近在通过 ssh 运行命令时遇到了一些奇怪的行为。我很想听听对以下行为的任何解释。
运行ssh localhost 'touch foobar &'会按预期创建一个名为foobar的文件:
[bob@server ~]$ ssh localhost 'touch foobar &'
[bob@server ~]$ ls foobar
foobar
但是运行相同的命令但使用-t 选项强制伪tty 分配无法创建foobar:
[bob@server ~]$ ssh -t localhost 'touch foobar &'
Connection to localhost closed.
[bob@server ~]$ echo $?
0
[bob@server ~]$ ls foobar
ls: cannot access foobar: No such file or directory
我目前的理论是,因为触摸进程正在后台运行,所以在进程有机会运行之前分配和取消分配伪 tty。当然,添加一秒钟的睡眠可以让触摸按预期运行:
[bob@pidora ~]$ ssh -t localhost 'touch foobar & sleep 1'
Connection to localhost closed.
[bob@pidora ~]$ ls foobar
foobar
如果有人有明确的解释,我会很感兴趣。谢谢。
【问题讨论】:
-
我想就是这样。后台进程连接到 tty 并且 tty 死亡将其杀死。试试
nohup touch foobar &看看是否可行和/或touch foobar </dev/null >/dev/null 2>&1。 -
ssh -t localhost 'touch foobar < /dev/null > /dev/null 2>&1 & '和ssh -t localhost 'nohup touch foobar & '产生相同的行为。 -
他们无法创建文件?我得到了这里创建的文件,即使是为了记录的原始版本。
-
是的,这两个命令都没有创建文件。
-
touch foobar </dev/null >/dev/null 2>&1不会阻止进程由其控制 TTY 发出信号。 nohup 情况可能是一种竞争条件——nohup在阻止信号之前被发出信号。