我有一个关于linux进程的问题,但我不明白。
这个问题来自《Advanced Bash Script》一书,代码在这里:(我已经简化了)
#! /bin/bash
# spawn.sh
sleep 1
sh $0 # fork a child process here and into infinite loop
exit 0 # the script will never come here
当我在shell中运行./spawn.sh时,进程会卡在那里,一段时间后会有很多“sh spawn.sh”进程。
我认为现在进程之间的关系是这样的:
./spawn.sh 进程(pid: 10000) ---> 子进程(pid: 10001) ---> 子进程(pid:1002) --->子进程(pid:1003) ---> 等等
当我在 Shell 中按 Control-C 时,父进程结束,它的所有子进程也结束。这是我无法理解的地方。为什么所有处理过的 child 都会灭亡?我认为进程之间的关系应该是这样的:
init(pid: 1) ---> 子进程(pid: 10001) ---> 子进程(pid:1002) --->子进程(pid:1003) ---> 等等
但事实是好像父进程在结束时向其子进程发送信号,从而导致所有子进程一一灭亡。这是正常现象还是shell脚本的一个特性?
提前非常感谢您。
最佳答案
when i push Control-C in the Shell, the parent process is over, and all its child processes are over too. this is where i can not understand. why all child processed perish
当您按下 Ctrl-C 时,SIGINT 不仅会发送到父进程,还会发送到整个进程组。这意味着所有三个进程都会收到 SIGINT,因此它们会死亡。要查看实际效果,请添加
trap "process $$ exiting" INT
查看 child 不会对其 parent 的死亡使用react的一种快速方法是让脚本生成一个 child ,然后杀死 parent 。
关于linux - Linux bash脚本中父进程和子进程的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205677/