linuxbashforkchild-process

I want to initiate a bash child process and when assign child PID to an array the command {./child2.sh &} won't execute


I want a simple linux program to create 6 child process using a for loop and capture each of the child PID in array. The problem is if I assign the command to variable the command {./child2.sh &} won't execute anymore.

I tried doing something like

cid[$i]=./child2.sh &  cid[$i]=./child2.sh & cid[$i]=./child2.sh &

Solution

  • The pid of the latest program launched in background in stored in $!. Try the following:

    for i in 0 1 2 3 4 5
    do
      ./child2.sh &
      cid[$i]=$!
    done
    

    To get the exit status of the terminated processes, use waitcommand:

    for i in 0 1 2 3 4 5
    do
      ./child2.sh &
      cid[$i]=$!
    done
    
    for i in 0 1 2 3 4 5
    do
      wait ${cid[$i]}
      echo "Status of child#$i (${cid[$i]}): $?"
    done