Linux

Bash:獨立於父PID執行命令?

  • November 17, 2018

執行此test.sh腳本:

#!/bin/bash
sleep 15 & sleep 2000

然後,查看正在執行的程序$ ps auxfwww | grep -i [2]000 -B 10,我得到以下1188611887PID:

user      7070  0.0  0.0   4504  1444 ?        Ss   Nov15   0:00          \_ /bin/sh /etc/xdg/xfce4/xinitrc -- /etc/X11/xinit/xserverrc
user      7081  0.0  0.0 324540 14064 ?        Sl   Nov15   0:00          |   \_ xfce4-session
user      7100  0.0  0.3 562128 62800 ?        Sl   Nov15   0:48          |       \_ tilix
user     23644  0.0  0.0  31132  6136 pts/11   Ss   14:32   0:00          |       |   \_ /bin/bash
user     11884  0.0  0.0  20024  3044 pts/11   S+   14:58   0:00          |       |   |   \_ /bin/bash ./test.sh
user     11886  0.0  0.0  14776   700 pts/11   S+   14:58   0:00          |       |   |       \_ sleep 15
user     11887  0.0  0.0  14776   704 pts/11   S+   14:58   0:00          |       |   |       \_ sleep 2000

是否可以sleep 2000完全獨立於父程序執行命令?例如:

user      7070  0.0  0.0   4504  1444 ?        Ss   Nov15   0:00          \_ /bin/sh /etc/xdg/xfce4/xinitrc -- /etc/X11/xinit/xserverrc
user      7081  0.0  0.0 324540 14064 ?        Sl   Nov15   0:00          |   \_ xfce4-session
user      7100  0.0  0.3 562128 62800 ?        Sl   Nov15   0:48          |   |   \_ tilix
user     23644  0.0  0.0  31132  6136 pts/11   Ss   14:32   0:00          |   |   |   \_ /bin/bash
user     11884  0.0  0.0  20024  3044 pts/11   S+   14:58   0:00          |   |   |   |   \_ /bin/bash ./test.sh
user     11886  0.0  0.0  14776   700 pts/11   S+   14:58   0:00          |   |   |   |       \_ sleep 15
user     XXXXX  0.0  0.0  XXXXX   XXX XXXXXX   S+   XX:XX   0:00          \_ sleep 2000

是的,這是可能的。

您在這裡想要的是重新設置該過程。一旦原始父程序終止,Unix 會將程序重新設置為 PID 1。

因此,您需要做的就是擁有出口的原始父級。sleep 2000

您可以通過sleep 2000從子外殼啟動背景來做到這一點。

就像是:

#!/bin/bash
sleep 15 &
( sleep 2000 & )
# do something else here, like:
sleep 1
echo "=== Listing 'sleep' process tree: ==="
ps auxfwww | grep -i [2]000 -B 10
echo "=== All done. ===

引用自:https://unix.stackexchange.com/questions/482419