gpt4 book ai didi

linux - 如何添加nohup? - 将标准输入重定向到程序和背景

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:45:14 27 4
gpt4 key购买 nike

我有一个程序 prog 接受这样的标准输入:

prog < test.txt

但是处理过程需要相当多的时间,所以一旦输入被读取,该过程就应该在后台进行。

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

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

最佳答案

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 的兼容性,那么您将希望将标准输入捕获到一个文件中(可能会以非常大的效率成本为代价):

#!/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"' &

关于linux - 如何添加nohup? - 将标准输入重定向到程序和背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com