How to get PID from forked child process in shell script

前端 未结 2 1242
情歌与酒
情歌与酒 2021-02-02 08:54

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

Below is my code:

#/bin/sh
fpfunction(){
    n=1
    while (($n<20))
    do
        ech         


        
相关标签:
2条回答
  • 2021-02-02 09:18

    From the Bash manual:

    !

    Expands to the process ID of the most recently executed background (asynchronous) command.

    i.e., use $!.

    0 讨论(0)
  • 2021-02-02 09:24

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

    fpfunction &
    child_pid=$!
    parent_pid=$$
    

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

    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:

    for ((n = 1; n < 20; ++n)); do
    do
        echo "Hello World-- $n times"
        sleep 2
        echo "Hello World2-- $n times"
    done
    
    0 讨论(0)
提交回复
热议问题