Linux 如何从shell脚本中的分叉子进程获取PID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17356591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get PID from forked child process in shell script
提问by Sam
I believe I can fork 10 child processes from a parent process.
我相信我可以从父进程分叉 10 个子进程。
Below is my code:
下面是我的代码:
#/bin/sh
fpfunction(){
n=1
while (($n<20))
do
echo "Hello World-- $n times"
sleep 2
echo "Hello World2-- $n times"
n=$(( n+1 ))
done
}
fork(){
count=0
while (($count<=10))
do
fpfunction &
count=$(( count+1 ))
done
}
fork
However, how can I get the pid from each child process I just created?
但是,如何从我刚刚创建的每个子进程中获取 pid?
采纳答案by John Kugelman
The PID of a backgrounded child process is stored in $!
.
后台子进程的 PID 存储在$!
.
fpfunction &
child_pid=$!
parent_pid=$$
For the reverse, use $PPID
to get the parent process's PID from the child.
相反,用于$PPID
从子进程获取父进程的 PID。
fpfunction() {
local child_pid=$$
local parent_pid=$PPID
...
}
Also for what it's worth, you can combine the looping statements into a single C-like for loop:
同样值得一提的是,您可以将循环语句组合成一个类似 C 的 for 循环:
for ((n = 1; n < 20; ++n)); do
do
echo "Hello World-- $n times"
sleep 2
echo "Hello World2-- $n times"
done
回答by Oliver Charlesworth
From the Bash manual:
从Bash 手册:
!
Expands to the process ID of the most recently executed background (asynchronous) command.
!
扩展到最近执行的后台(异步)命令的进程 ID。
i.e., use $!
.
即,使用$!
.