關於 bash &(and, ampersand) 與 nohup 運作原理

starzodiac
Oct 23, 2020

--

今天同事忽然討論起 bash & 跟 nohup 之間的差異,花了一點時間 survey 了一下,簡單總結:

* bash &(and, ampersand)

用法: [CMD][2>&1 [> FILE]] &

加上 & 後 bash 會在背景執行 [CMD]

如果輸入 fg 會再將該 [CMD] 變回前景執行,原本以為跟 deamon 工作方式,但結果發現不太一樣

但是這樣stdoutstderr還是會直接在前景出現,造成靈異現象(笑)

通常會跟 2>&1 [> FILE]搭配使用,2>&1會把 stderr導到stdout> [FILE]會把stdout導到[FILE]中。

ref:

https://unix.stackexchange.com/questions/86247/what-does-ampersand-mean-at-the-end-of-a-shell-script-line

* 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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response