Search code examples
linuxshellpid

How to get PID from forked child process in shell script


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
        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?


Solution

  • The PID of a backgrounded child process is stored in $!, and the current process is $$:

    fpfunction &
    child_pid=$!     # in parent process, child's pid is $!
    parent_pid=$$    # in parent process, parent's pid is $$
    

    When in the backgrounded function, the child processes's PID is $BASHPID rather than $$, which is now the parent's PID:

    fpfunction() {
        local child_pid=$BASHPID   # in child process, child's pid is $BASHPID
        local parent_pid=$$        # in child process, parent's pid is $$
        ...
    }
    

    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
        echo "Hello World-- $n times"
        sleep 2
        echo "Hello World2-- $n times"
    done