我想通过将其存储在变量中并将其导出或其他方式将父子进程ID报告给父级。这怎么可能?下面是一个小例子。
例子。
parent.sh
./child.sh &
wait
sleep 10
echo $grandchild_pid
child.sh
./grandchild.sh &
export grandchild_pid=$!
答案 0 :(得分:4)
一种方法是使用FIFO:
tempdir=$(mktemp -t -d fifodir.XXXXXX) # tempdir for our named pipe
trap 'rm -rf "$tempdir"' EXIT # ...arrange for it to be deleted on exit
mkfifo "$tempdir/child" # create our temporary FIFO
./child.sh 3>"$tempdir/child" & # start our background process, FD 3 to the FIFO
sleep 10 # do whatever
read grandchild_pid <"$tempdir/child" # read from the FIFO
echo "Our grandchild's PID is $grandchild_pid"
......以及child.sh
:
./grandchild.sh 3>&- & # start the grandchild in the background
(echo "$!" >&3 &) # write PID to FD3 in background so we don't block on the parent
exec 3>&- # close the FD from the child, so only the backgrounded echo has it
答案 1 :(得分:1)
你可以找到所有的孙子&#34;像这样的过程:
{{1}}
答案 2 :(得分:1)
一个解决方案,但不是最好的解决方案是将您的孩子和孙子的pids打印在文件上。然后父母可以捕获这个文件并获取数据。
一个小例子:
家长流程:
#!/bin/bash
echo "Im the parent"
rm .pids.childs
./child.sh &
wait
echo "my son is: $(cat .pids.childs | grep SON)"
echo "my gchild is: $(cat .pids.childs | grep GCH)"
echo "Parent Finish"
exit 0
子进程:
#!/bin/bash
echo "Im the child"
echo "SON_PID=$$" >> .pids.childs
./gchild.sh &
wait
echo "Child Finish"
exit 0
GrandChild流程: #!/斌/庆典
echo "Im the gchild"
echo "GCH_PID=$$" >> .pids.childs
echo "gchild Finish"
exit 0
这不是一个很好的解决方案但它有效