關於 bash &(and, ampersand) 與 nohup 運作原理
今天同事忽然討論起 bash & 跟 nohup 之間的差異,花了一點時間 survey 了一下,簡單總結:
* bash &(and, ampersand)
用法: [CMD][2>&1 [> FILE]] &
加上 &
後 bash 會在背景執行 [CMD]
如果輸入 fg
會再將該 [CMD] 變回前景執行,原本以為跟 deamon 工作方式,但結果發現不太一樣
但是這樣stdout
跟stderr
還是會直接在前景出現,造成靈異現象(笑)
通常會跟 2>&1 [> FILE]
搭配使用,2>&1
會把 stderr
導到stdout
,> [FILE]
會把stdout
導到[FILE]
中。
ref:
* nohup
用法: nohup [CMD][>[FILE]]
為 GNU 提供的 coreutil,會把stderr
導到stdout
,並導入到[FILE]
中(Deafault: nohup.out),詳細看以下內容:
If standard input is a terminal, redirect it from /dev/null.
If standard output is a terminal, append output to 'nohup.out' if possible,
'$HOME/nohup.out' otherwise.
If standard error is a terminal, redirect it to standard output.
To save output to FILE, use 'nohup COMMAND > FILE'.
工作原理是執行 nohup 後會利用 execvp
去執行 CMD
//redirecting_stdout
out_fd = (redirecting_stdout ? fd_reopen (STDOUT_FILENO, file, flags, mode) : open (file, flags, mode));
...//redirecting_stderr
dup2 (out_fd, STDERR_FILENO)
...signal (SIGHUP, SIG_IGN);
char **cmd = argv + optind;
execvp (*cmd, cmd);
ref:
https://unix.stackexchange.com/questions/316186/how-does-nohup-work
source code: https://github.com/coreutils/coreutils/blob/6a3d2883fed853ee01079477020091068074e12d/src/nohup.c