bash 运行 nc 和符号终止程序

bash running nc with ampersand terminates program

我想 运行 通过 & nc,然后在需要时从 /proc 文件系统手动将数据输入到标准输入中。所以问题是:

如果我运行nc 127.0.0.1 1234 &

在后台编程 运行s,我可以在 stdin 中写入任何我想要的东西。但是,如果我创建 test.sh 并添加

#!/bin/bash
nc 127.0.0.1 1234 &
sleep 20

它连接到 1234 并立即终止(甚至不等待 20 秒)。为什么?我怀疑它是从某个地方写的标准输入。

如果我理解你的目的,你想手动将数据提供给 nc,然后发送给客户端。

您可以为此目的使用命名管道。

cat /tmp/f | ./parser.sh 2>&1 | nc -lvk 127.0.0.1 1234 > /tmp/f

其中 /tmp/f 是使用 mkfifo /tmp/f

制成的烟斗

任何你想提供给 nc 的东西都可以在 parser.sh

中回显

有趣的问题。

bash 联机帮助页指出:

   If  a  command  is  followed  by a & and job control is not active, the
   default standard input for the command is  the  empty  file  /dev/null.
   Otherwise,  the  invoked  command  inherits the file descriptors of the
   calling shell as modified by redirections.

如果您在 shell 脚本(带有作业控制)之外调用 nc 127.0.0.1 1234 < /dev/null,结果相同。

您可以像这样更改 bash 脚本以使其工作:

#!/bin/bash
nc 127.0.0.1 1234 < /dev/stdin &
sleep 20