我想通过 & 运行 nc,然后随时从/proc 文件系统手动将数据输入 stdin。 所以问题是:
如果我跑nc 127.0.0.1 1234 &
程序在后台运行,我可以在 stdin 中编写任何我想要的内容。 但是,如果我创建 test.sh 并添加
#!/bin/bash
nc 127.0.0.1 1234 &
sleep 20
它连接到 1234 并立即终止(甚至不等待 20 秒)。 为什么?我怀疑它从某个地方写了 stdin。
有趣的问题。
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
如果我的目的正确,您希望将数据手动提供给 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
中回声