Skip to content

Instantly share code, notes, and snippets.

@bluekezza
Created June 9, 2020 11:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluekezza/e511f3f4429939a0f9ecb6447099b3dc to your computer and use it in GitHub Desktop.
Save bluekezza/e511f3f4429939a0f9ecb6447099b3dc to your computer and use it in GitHub Desktop.
Calling a function using nohup
function function_to_run {
while true
do
echo "function1"
sleep 1
done
}
function main {
( # start a group. The statements will be executed in a sub-shell (see https://www.gnu.org/software/bash/manual/html_node/Command-Grouping.html#Command-Grouping)
trap '' HUP INT # catch the SIGHUP and SIGINT signals and ignore them (see trap in https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#Bourne-Shell-Builtins)
function_to_run # call the function to be executed
) \ # mark the end of the group. We can now control the groups file handles and execution
</dev/null \ # disconnect our forked process from stdin by pointing stdin to /dev/null
2>&1 \ # anything written to stderr should instead be written to stdout
1>nohup.out \ # redirect stdout (which also includes stderr from above) to the file
& # execute the command asychronously: https://www.gnu.org/software/bash/manual/html_node/Lists.html#Lists
}
main
@ams-tschoening
Copy link

While the above makes the function run async in the background of some sort, from my understanding it is not fully detached from the parent executing script. Reason is the redirection of STDOUT into the file, that is done by the parent shell and makes it a zombie after main itself ends. One gets a fully detached subshell without a parent zombie by redirecting output within the subshell and detaching the parent shell entirely:

(
trap '' HUP INT
function_to_run > "PATH_TO_SOME_FILE"
) '/dev/null' > '/dev/null' 2> '/dev/null' &

At least this is a problem I ran into with the proposed solution in some special backup context, where realyl concurrent and independent execution of scripts was necessary:

https://superuser.com/a/1718686/308859

Additionally, from my understanding the order of redirecting STDERR and STDOUT might be wrong according to the manpage of BASH:

Note that the order of redirections is significant. For example, the command

ls > dirlist 2>&1
directs both standard output and standard error to the file dirlist, while the command
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment