37

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?

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
Sam
  • 4,241
  • 13
  • 42
  • 76

2 Answers2

71

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
    echo "Hello World-- $n times"
    sleep 2
    echo "Hello World2-- $n times"
done
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
11

From the Bash manual:

!

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

i.e., use $!.

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
  • 1
    so $! will give the pid of currently running process whether it is a parent process or a child process? – y_159 Aug 09 '20 at 18:54
  • and also will it give the pid of most recently executed background process or executing process. – y_159 Aug 09 '20 at 19:20