linux - bash 运行 nc 和符号终止程序

标签 linux bash shell pipeline

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

如果我运行 nc 127.0.0.1 1234 &

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

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

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

最佳答案

有趣的问题。

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.

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

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

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

关于linux - bash 运行 nc 和符号终止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35645936/

相关文章:

linux - 同一主机上 2 个接口(interface)之间的 iperf

bash - 如何从 Chrome 复制 cookie?

linux - 使用 env 变量指定 makefile

shell - 如何在文本的某一行末尾附加一些内容

linux - 安装在 ubuntu 上的 Snort 不向 syslog 发送警报

c - realloc 是否保持 posix_memalign 的内存对齐?

linux - 如何从后台进程 linux shell 脚本中获取结果?

bash - unix awk 列等于一个变量

java - 如何从 jar 文件执行 shell 脚本

java - shell脚本没有完全从java执行