Created
June 9, 2020 11:45
-
-
Save bluekezza/e511f3f4429939a0f9ecb6447099b3dc to your computer and use it in GitHub Desktop.
Calling a function using nohup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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: