2

I have a bash script, in which I call function in a background:

process_manager $1 $2 $3 &

The function runs / executes commands that are passed as an argument in the background.

How can I get a list of child processes in the function process_manager ?

I tried doing that:

process_manager () {
  count=$1
  interval=$2
  cmd=$3
  bash_pid=$$
  last_pid=$!

  echo "bash_pid: $bash_pid, ppid: $PPID, last_pid: $last_pid"
  $cmd &
  $cmd &
  sleep 30 &
}

process_manager $1 $2 $3 &
process_manager $1 $2 $3 &
process_manager $1 $2 $3 &

But here function process_manager won't display $! or $last_pid when its called for the first time.

How should I get $last_pid in that situation and to be able to access children process list?

3

$$ contains the pid of the shell that was executed to interpret the script. It's the same in every subshell of that shell.

$! contains the pid of the last child command run in background (with & or coproc or process substitution)

In the command run itself in background, $! it not set. $! is meant for the parent so it can wait or kill its child.

bash has a $BASHPID variable that contains the pid of the current subshell.

It's not always clear what process it is.

In:

echo "$BASHPID"

It's the pid of the process that interpreted that echo command, but in

/bin/echo "$BASHPID"

which does fork a process, $BASHPID does not report the pid of that forked process but the pid of the parent. While in:

/bin/echo "$BASHPID" &

(the only difference being that the parent doesn't wait for its child), $BASHPID reports the pid of the forked process:

$ bash -c 'echo "$$"; echo "$BASHPID"; /bin/echo "$BASHPID"; /bin/echo $BASHPID &'
3264
3264
3264
3266

In you case though, you can safely do:

process_manager () {
  pid_of_last_command_run_in_background=$!
  mypid=$BASHPID
  cmd &
  cmd1pid=$!
  cmd &
  cmd2pid=$!
}

$pid_of_last_command_run_in_background will be the pid of the last command run in background (by the current subshell, or its parent or its grandparent). That's why you get something in $last_pid in the second run (the pid of the previous process_manager) and not in the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.