可以通过非父母程序杀死儿童吗?

时间:2018-08-15 20:28:25

标签: unix posix parent-child

我正在制作一个项目,其中 parent 派生一个 terminator 进程,该进程杀死父级的一个随机子级。看来这会带来一些问题。

可以吗?

2 个答案:

答案 0 :(得分:0)

允许。在parent.sh

中编写以下代码
terminator() {
   sleep 2;
   echo "(terminator) Going to kill Pid $1"
   kill -9 "$1" && echo "(terminator) Pid $1 killed"
}

sleep 7 &
sleep 7 &
sleep 7 &
pid=$!
echo "Random pid=${pid} will be killed"
sleep 7 &
sleep 7 &
terminator ${pid} &
echo "All started"
ps -ef | sed -n '1p; /sleep 7/p'
sleep 3
echo "After kill"
ps -ef | sed -n '1p; /sleep 7/p'

后台进程是子进程。终止子会在2秒后杀死另一个随机子。

Random pid=6781 will be killed
All started
UID        PID  PPID  C STIME TTY          TIME CMD
notroot   6779  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6780  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6781  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6782  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6783  6777  0 16:59 pts/0    00:00:00 sleep 7
(terminator) Going to kill Pid 6781
(terminator) Pid 6781 killed
parent.sh: line ...:  6781 Killed                  sleep 7
After kill
UID        PID  PPID  C STIME TTY          TIME CMD
notroot   6779  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6780  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6782  6777  0 16:59 pts/0    00:00:00 sleep 7
notroot   6783  6777  0 16:59 pts/0    00:00:00 sleep 7

答案 1 :(得分:0)

不仅允许这样做:以同一用户或root用户身份运行的任何进程都可以杀死任何其他进程。

在终端中以我的用户ID身份运行时,我可以使用我的用户ID杀死任何东西。甚至我正在运行的终端。或者我的GUI进程。

在Unix OS类型中,唯一可以杀死的进程是PID 1 aka init。因为杀死init将立即导致内核崩溃。如果PID 1出于某种原因(例如内部错误和分段错误)退出,则会立即导致内核崩溃。

相关问题