答案1
会话 ID
iTerm2 --server login -fp
在这种情况下,会话 ID 实际上是 pid ,ps
但在 OS X 中无法正确显示。您可以使用下面的 C 代码来确认这一点。
1 #include <stdio.h>
2 #include <unistd.h>
3
4 int main() {
5 printf("pid: %d, process groupd id: %d, session ID: %d, ppid: %d\n",getpid(), getpgid(0), getsid(0), getppid());
6 }
$ gcc getsid.c -o getsid ; ./getsid
pid: 25472, process groupd id: 25472, session ID: 25236, ppid: 25239
会话领导者是进程 25236,它是iTerm2 --server login -fp
$ pstree -p $$
-+= 00001 root /sbin/launchd
\-+= 25234 shaobirui /Applications/iTerm.app/Contents/MacOS/iTerm2
\-+= 25236 shaobirui /Applications/iTerm.app/Contents/MacOS/iTerm2 --server login -fp shaobirui
\-+= 25237 root login -fp shaobirui
\-+= 25239 shaobirui -bash
\-+= 25329 shaobirui pstree -p 25239
\--- 25330 root ps -axwwo user,pid,ppid,pgid,command
另一个巧妙的方法是检查STAT
字段,您可以看到Ss
,第二个字段s
实际上意味着会话领导者。
$ ps -j
USER PID PPID PGID SESS JOBC STAT TT TIME COMMAND
shaobirui 25236 25234 25236 0 0 Ss s000 0:00.03 /Applications/iTerm.app/Contents/MacOS/iTerm2 --server login -fp shaobirui
shaobirui 25239 25237 25239 0 1 S s000 0:00.05 -bash
为何儿童会被杀害?
当会话领导者退出时,它将向其所有后代发送 SIGHUP,默认情况下会终止进程。我在两个终端仿真器中重现了它:iTerm2 和 OS X termianl。
在iTerm2中:
$ tty
/dev/ttys000
$ cat test.sh
trap "echo $$ got SIGUP > /tmp/out.txt;exit" 1
echo $$ is sleeping
sleep 5555
$ bash test.sh
25000 is sleeping
在 OS X 终端中:
$ pstree -p 25000
-+= 00001 root /sbin/launchd
\-+= 24875 shaobirui /Applications/iTerm.app/Contents/MacOS/iTerm2
\-+= 24877 shaobirui /Applications/iTerm.app/Contents/MacOS/iTerm2 --server login -fp shaobirui
\-+= 24878 root login -fp shaobirui
\-+= 24879 shaobirui -bash
\-+= 25000 shaobirui bash test.sh
\--- 25001 shaobirui sleep 5555
$ ps -j -o tpgid 24875 24878 24879 25000 25001
USER PID PPID PGID SESS JOBC STAT TT TIME COMMAND TPGID
shaobirui 24875 1 24875 0 1 S ?? 0:07.97 /Applications/iT 0
shaobirui 24877 24875 24877 0 0 Ss s000 0:00.04 /Applications/iT 25000
shaobirui 24879 24878 24879 0 1 S s000 0:00.03 -bash 25000
shaobirui 25000 24879 25000 0 1 S+ s000 0:00.00 bash test.sh 25000
shaobirui 25001 25000 25000 0 1 S+ s000 0:00.00 sleep 5555 25000
shaobirui 22134 22133 22134 0 1 S s001 0:00.40 -bash 25021
$ kill 24877
# all processes in that session are gone due to SIGHUP
$ ps -j -o tpgid 24875 24878 24879 25000 25001
USER PID PPID PGID SESS JOBC STAT TT TIME COMMAND TPGID
shaobirui 22134 22133 22134 0 1 S s001 0:00.41 -bash 25032
$ cat /tmp/out.txt
25000 got SIGUP