mvorisek
mvorisek

Reputation: 3428

How to add nohup? - Redirect stdin to program and background

I have a program prog that takes stdin input like this:

prog < test.txt

But the processing takes quite a lot time, so once the input is read, it the process should background.

From this answer https://unix.stackexchange.com/a/71218/201221 I have working solution, but without nohup. How modify it to use nohup too?

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

Upvotes: 2

Views: 1308

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295472

disown is a shell builtin which tells bash to remove a process from its recordkeeping -- including the recordkeeping that forwards HUP signals. Consequently, if stdin, stdout and stderr are all redirected or closed before the terminal disappears, there's absolutely no need for nohup so long as you use 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

If you really need compatibility with POSIX sh, then you'll want to capture stdin to a file (at a potentially very large cost to efficiency):

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

Upvotes: 3

Georgi Georgiev
Georgi Georgiev

Reputation: 1623

From what I see the following code is contained in a separate shell file:

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

So, why not try just:

nohup the_file.sh &

Upvotes: 0

Related Questions