如何从Shell脚本中的派生子进程中获取PID [英] How to get PID from forked child process in shell script

查看:1190
本文介绍了如何从Shell脚本中的派生子进程中获取PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信我可以从一个父进程中派生10个子进程.

I believe I can fork 10 child processes from a parent process.

下面是我的代码:

#/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

但是,如何从刚刚创建的每个子进程中获取pid?

However, how can I get the pid from each child process I just created?

推荐答案

后台子进程的PID存储在$!中.

The PID of a backgrounded child process is stored in $!.

fpfunction &
child_pid=$!
parent_pid=$$

反之,请使用$PPID从子级获取父进程的PID.

For the reverse, use $PPID to get the parent process's PID from the child.

fpfunction() {
    local child_pid=$$
    local parent_pid=$PPID
    ...
}


对于它的价值,您还可以将循环语句组合成一个类似C的for循环:


Also for what it's worth, you can combine the looping statements into a single C-like for loop:

for ((n = 1; n < 20; ++n)); do
do
    echo "Hello World-- $n times"
    sleep 2
    echo "Hello World2-- $n times"
done

这篇关于如何从Shell脚本中的派生子进程中获取PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆