2

I am using the following Bash script. What I don't understand is why the parent PID and the current PID are not matching. For example:

#!/bin/bash

my_background_function() {
  echo "Starting background function..."
  echo "Current pid in function $$"
  echo "Parent pid in function $PPID"
  sleep 5 # Simulate some work
  echo "Background function finished."
}

echo "Current pid" $$
echo "Parent pid" $PPID
my_background_function &
background_pid=$!

echo "Main script continues while function runs in background."

wait $background_pid 

When I run the above command, I thought the current PID in the function would be a different value. However, when I run this, this is what I get:

Current pid 378780
Parent pid 363128
Main script continues while function runs in background.
Starting background function...
Current pid in function 378780
Parent pid in function 363128
Background function finished.

As you can see, the current PID is the same for the parent process and for the background process.

Thanks,

0

1 Answer 1

1

You are checking wrong variable.

From Bash manual :

($$) Expands to the process ID of the shell. In a subshell, it expands to the process ID of the invoking shell, not the subshell.

$$ is the PID of the invoking shell - the "first" parent shell.

$BASHPID holds the PID of the current shell.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.