使用管道在后台运行命令

hil*_*red 4 shell io-redirection

我正在rpi 上阅读这个问题,并注意到一条有趣的线让我思考:

mkfifo tcp.stream
nc -l -p 1234 > tcp.stream | omxplayer --live tcp.stream
Run Code Online (Sandbox Code Playgroud)

注意 io 重定向。STDOUT 被重定向两次!我担心的是 omxplayer 没有与任何可用的 STDIN 相关联可能有点难以控制,但我认为这确实具有在 omxplayer 退出时使用 SIGPIPE 杀死 nc 的优势。这是一个好主意吗?在某些奇怪的情况下,这值得推荐吗?

yae*_*shi 6

管道将立即关闭nc。当omxplayerdiesnc在写入 fifo 而不是管道时会收到 SIGPIPE。

最好nc在后台运行,以便您可以omxplayer通过标准输入保持控制。

mkfifo tcp.stream
nc -l -p 1234 > tcp.stream &
omxplayer --live tcp.stream
Run Code Online (Sandbox Code Playgroud)

但是,从 shell 的作业控制的角度来看,使用|而不是&实际上是有意义的。

使用|

$ mkfifo fifo
$ nc -l -p 1234 >fifo | cat fifo
Run Code Online (Sandbox Code Playgroud)

nc并且cat属于同一个进程组(PGID 9177)。

$ ps f -o pid,ppid,pgid,command
  PID  PPID  PGID COMMAND
 9095  1681  9095 bash
 9179  9095  9179  \_ ps f -o pid,ppid,pgid,command
 1691  1681  1691 bash
 9177  1691  9177  \_ nc -l -p 1234
 9178  1691  9177  \_ cat fifo
Run Code Online (Sandbox Code Playgroud)

他们都收到 SIGINT 然后在用户键入Ctrl+时退出C

使用&

$ mkfifo fifo
$ nc -l -p 1234 >fifo & cat fifo
[1] 9183
Run Code Online (Sandbox Code Playgroud)

nc并且cat属于不同的进程组(PGID 9183 和 9184)。

$ ps f -o pid,ppid,pgid,command
  PID  PPID  PGID COMMAND
 9095  1681  9095 bash
 9185  9095  9185  \_ ps f -o pid,ppid,pgid,command
 1691  1681  1691 bash
 9183  1691  9183  \_ nc -l -p 1234
 9184  1691  9184  \_ cat fifo
Run Code Online (Sandbox Code Playgroud)

在这种情况下,只有前台进程 ( cat) 在用户键入Ctrl+时收到 SIGINT C。如果nc还没有连接,它仍然在后台运行。

^C
$ jobs
[1]+  Running                 nc -l -p 1234 > fifo &
$ kill %
[1]+  Terminated              nc -l -p 1234 > fifo
Run Code Online (Sandbox Code Playgroud)