如何添加nohup? - 将stdin重定向到程序和背景

问题描述 投票:1回答:2

我有一个程序prog,它接受stdin输入,如下所示:

prog < test.txt

但是处理需要相当多的时间,因此一旦读取输入,该过程就应该是后台。

从这个答案https://unix.stackexchange.com/a/71218/201221我有工作的解决方案,但没有nohup。如何修改它以使用nohup

#!/bin/sh
{ prog <&3 3<&- & } 3<&0
linux bash shell pipe
2个回答
3
投票

disown是一个内置shell,它告诉bash从记录保存中删除一个进程 - 包括转发HUP信号的记录保存。因此,如果stdin,stdout和stderr在终端消失之前都被重定向或关闭,那么只要你使用nohup就绝对不需要disown

#!/bin/bash

logfile=nohup.out            # change this to something that makes more sense.
[ -t 1 ] && exec >"$logfile" # do like nohup does: redirect stdout to logfile if TTY
[ -t 2 ] && exec 2>&1        # likewise, redirect stderr away from TTY

{ prog <&3 3<&- & } 3<&0
disown

如果你真的需要与POSIX sh的兼容性,那么你会想要将stdin捕获到一个文件(效率可能非常高):

#!/bin/sh

# create a temporary file
tempfile=$(mktemp "${TMPDIR:-/tmp}/input.XXXXXX") || exit

# capture all of stdin to that temporary file
cat >"$tempfile"

# nohup a process that reads from that temporary file
tempfile="$tempfile" nohup sh -c 'prog <"$tempfile"; rm -f "$tempfile"' &

0
投票

从我看到以下代码包含在一个单独的shell文件中:

#!/bin/sh
{ prog <&3 3<&- & } 3<&0

所以,为什么不尝试:

nohup the_file.sh &
© www.soinside.com 2019 - 2024. All rights reserved.