问题
From the nohup documentation in info coreutils 'nohup invocation'
it states:
Exit status:
125 if `nohup' itself fails, and `POSIXLY_CORRECT' is not set
126 if COMMAND is found but cannot be invoked
127 if COMMAND cannot be found
the exit status of COMMAND otherwise
However, the only exit codes I've ever gotten from nohup have been 1 and 0. I have a nohup command that's failing from within a script, and I need the exception appropriately...and based on this documentation I would assume that the nohup exit code should be 126. Instead, it is 0.
The command I'm running is: nohup perl myscript.pl &
Is this because perl is exiting successfully?
回答1:
If your shell script runs the process with:
nohup perl myscript.pl &
you more or less forego the chance to collect the exit status from nohup
. The command as a whole succeeds with 0 if the shell forked and fails with 1 if the shell fails to fork. In bash
, you can wait for the background process to die and collect its status via wait
:
nohup perl myscript.pl &
oldpid=$!
...do something else or this whole rigmarole is pointless...
wait $oldpid
echo $?
The echoed $?
is usually the exit status of the specified PID (unless the specified PID had already died and been waited for).
If you run the process synchronously, you can detect the different exit statuses:
(
nohup perl myscript.pl
echo "PID $! exited with status $?" >&2
) &
And now you should be able to spot the different exit statuses from nohup
(eg try different misspellings: nohup pearl myscript.pl
, etc).
Note that the sub-shell as a whole is run in the background, but the nohup
is run synchronously within the sub-shell.
回答2:
As my understanding, the question was how to get the command status when it was running in nohup. As my experiences it was very little chance that you were able to get the COMMAND exit status even when it failed right away. Most time you just got the 'nohup COMMAND &' exit status unless you wait or synchronize as Jonathan mentioned. To check the COMMAND status right after nohup, I use:
pid=`ps -eo pid,cmd | awk '/COMMAND/ {print $1}'` if [ -z $pid ]; then echo "the COMMAND failed" else echo "the COMMAND is running in nohup" fi
来源:https://stackoverflow.com/questions/15650307/how-to-get-the-proper-exit-code-from-nohup