linux - Linux bash脚本中父进程和子进程的关系

标签 linux bash shell process pid

我有一个关于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/

相关文章:

bash - 在 bash 中静音 docker rm 命令

python - 有什么方法可以在更改代码时不重新启动而使用 django shell

PHP - 在 cron 作业中从 Amazon S3 读取大型 XML 文件导致进程内存不足

linux - 从具有路径的日志文件将文件恢复到其原始位置

bash - 配置或库 shell 脚本是否需要 shebang?

linux - DC/OS ssh 连接在端口 22 上被拒绝 - 预检

windows - 将 dos shell 目录与 emacs 对齐 'working directory'

shell - 以特定频率循环 VxWorks 中的命令

linux - 'make' 期间 config.status 错误

c - Linux 中 IPC 的 shmget