gpt4 book ai didi

c - 从叶子开始逐级修剪二叉流程树

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:08 25 4
gpt4 key购买 nike

我需要编写一个运行 C 程序的 bash 脚本,该程序使用 fork() 生成一个 n 深度的进程二叉树,然后从树的叶子开始逐级修剪它到根。

制作进程树的C代码非常简单。 You can see the full code here , 但 TL;DR 版本如下:

void tree(int n):
if (n==0) exit
rchild=fork()
if (parent)
lchild=fork()
if (left child)
tree(n-1)
else //right child
tree(n-1)
sleep(1000)

查看 pstree -pn PID 输出我注意到 child 的 PID 是连续的,所以我决定根据第一个实例的 PID 按数值终止进程。但也许是因为命令占用了 PID 值或其他系统进程,在脚本中运行代码会破坏 PID 的值,所以我的方法不再有效。我正在尝试通过使用 pstree 的输出直接获取 PID,但目前看来它会是一堆 sedawk 调用只是为了获得一个PID 级别。

这是我目前拥有的 bash 脚本:

#!/bin/bash

if [ ! -f "./fork.run" ]
then
>&2 echo 'Error: binary mising'
>&2 echo 'Generate it with "gcc -o fork.run fork.c"'
exit
fi

if [ "$1" == "" ]
then
>&2 echo "Error: you need to indicate the depth of the tree"
exit
fi

./fork.run $(( $1 - 1 )) &
fork=$! #store tree's PID
n=$1

echo "fork started with PID $fork"


while [ $n -gt 1 ]
do

echo "Tree of the process $fork:"
pstree -pn $fork

sleep 1

#calculation based on properties of the binary tree
min=$(( 2 ** (n - 1) + $fork ))
max=$(( (2 ** n) - 1 + $fork ))

echo "starting trim: level $n"


for i in `seq $min $max`
do
echo "killing $i"
kill $i #I also tried kill -9 $i, but it's the same.
done

sleep 1

echo "processes from $min to $max trimmed"

let n--
done

pstree -pn $fork

sleep 1

echo "starting trim: level $n (final)"

kill $fork

sleep 1

echo "initial process ($fork) trimmed"

最佳答案

it seems that it will be a mess of sed and awk calls just to get one level of PIDs.

好吧,awk 并不太乱。 while 循环的以下替换使用 awk 脚本处理 pstree 输出,该脚本确定(基于每行中的位置)包含的进程所属的树级别并杀死所选级别 n 上的进程。

while [ $n -gt 1 ]
do
echo "Tree of the process $fork:"
pstree -p $fork
sleep 1
echo "starting trim: level $n"
pstree -pl $fork |
gawk -vn=$n '
/^[^ ]/ { level = 1; start[1] = 1 } # line starting with non-space has top level
/^ / { level = trats[match($0, "[|`]-")] } # determine first level of line from position of |- or `-
{ while (i = match(substr($0, start[level]), ")-[-+]-"))
{ start[level+1] = start[level]+i+1; ++level; trats[start[level]] = level } # hash level by position
if (match(substr($0, start[n]), "^.-[^(]+.([0-9]+)", p)) { print "killing "p[1]; system("kill "p[1]) }
} '
sleep 1
echo "processes trimmed"
let n--
done

关于c - 从叶子开始逐级修剪二叉流程树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58045338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com