使用exec bc 執行後使用ctrl+d 會直接退出已經登陸的用戶,而直接執行bc卻不會。。這是為什麼,可以通過其他手段中斷卻不註銷登陸嗎?此外還有啥區別?謝謝各位


謝邀。樓主為何不看一下exec命令的man

The argument to exec is a command_line for another command. exec runs this command without creating a new process. Some people picture this as overlaying the command on top of the currently executing KornShell. When the command exits, control returns to the parent of the shell.

意思是,exec命令執行時並不創建一個新的進程,而是直接取代當前進程。

更多可以瞭解exec函數族。

Fork-exec

Linux下Fork與Exec使用
我必須承認,exec (和相關的進程樹)概念是 UNIX 新手永遠迷惑的一點。簡單說,隨著一個進程啟動另一個進程(如你從 bash 啟動 bc,或者 bash 啟動 make 再啟動 gcc)之後,各個進程之間形成了一個樹形結構,可以用 pstree 命令查看:

$ pstree -c
init─┬─acpid
├─atd
├─cron
├─dbus-daemon
├─dhclient3
├─getty
├─getty
├─getty
├─getty
├─getty
├─getty
├─nginx─┬─nginx
│ ├─nginx
│ ├─nginx
│ └─nginx
├─postgres─┬─postgres
│ ├─postgres
│ ├─postgres
│ └─postgres
├─pptpd
├─rsyslogd─┬─{rsyslogd}
│ ├─{rsyslogd}
│ └─{rsyslogd}
├─sshd───sshd───sshd───bash───pstree
├─udevd─┬─udevd
│ └─udevd
├─upstart-socket-
├─upstart-udev-br
└─whoopsie───{whoopsie}

這裡 init 啟動了系統裏所有其它進程,其中某些又啟動了其它進程,比如其中 sshd 依序啟動了兩個 sshd 子進程,最後啟動了我的 bash,然後是這個 pstree 命令自己。

互動式 shell 多數時候在執行一個程序的時候,都在等待子進程結束以便開始重新響應用戶輸入;比如這個 pstree 結束之後,bash 才開始重新接受我的命令輸入。如果我確定之後不需要這個 bash 繼續運行,那麼在被啟動程序(這裡是 pstree)運行的過程中,這個 bash 自己已經沒有任何意義了。如果用 exec pstree 的話,bash 不必啟動一個」子「進程,而直接在自身內部執行 pstree 命令,效果如下:

$ exec pstree -c
init─┬─acpid
├─atd
├─cron
├─dbus-daemon
├─dhclient3
├─getty
├─getty
├─getty
├─getty
├─getty
├─getty
├─nginx─┬─nginx
│ ├─nginx
│ ├─nginx
│ └─nginx
├─postgres─┬─postgres
│ ├─postgres
│ ├─postgres
│ └─postgres
├─pptpd
├─rsyslogd─┬─{rsyslogd}
│ ├─{rsyslogd}
│ └─{rsyslogd}
├─sshd───sshd───sshd───pstree
├─udevd─┬─udevd
│ └─udevd
├─upstart-socket-
├─upstart-udev-br
└─whoopsie───{whoopsie}

注意其中 sshd 的部分,少了 bash。這個內容列印之後,我的 ssh 進程自動結束了,因為 bash 被替換為 pstree 不復存在,而 pstree (或題目中的 bc)執行之後就自己退出了。


find / -name mygirl -exec mv {} mywife ;


推薦閱讀:
查看原文 >>
相關文章