Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $$ returning the same id as the parent process?

People also ask

What is the parent ID of a process?

What is the PPID? In addition to a unique process ID, each process is assigned a parent process ID (PPID) that tells which process started it. The PPID is the PID of the process's parent.

What is $$ bash?

$$ is a Bash internal variable that contains the Process ID (PID) of the shell running your script. Sometimes the $$ variable gets confused with the variable $BASHPID that contains the PID of the current Bash shell.

How do I display the process ID PID of the current shell?

To get the PID of the last executed command type: echo "$!" Store the pid of the last command in a variable named foo: foo=$! Print it, run: echo "$foo"

Does every process have a parent process?

Every process (except process 0) has one parent process, but can have many child processes. The operating system kernel identifies each process by its process identifier.


$$ is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":

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

In bash 4, you can get the process ID of the child with BASHPID.

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634

You can use one of the following.

  • $! is the PID of the last backgrounded process.
  • kill -0 $PID checks whether it's still running.
  • $$ is the PID of the current shell.

  1. Parentheses invoke a subshell in Bash. Since it's only a subshell it might have the same PID - depends on implementation.
  2. The C program you invoke is a separate process, which has its own unique PID - doesn't matter if it's in a subshell or not.
  3. $$ is an alias in Bash to the current script PID. See differences between $$ and $BASHPID here, and right above that the additional variable $BASH_SUBSHELL which contains the nesting level.

Try getppid() if you want your C program to print your shell's PID.


this one univesal way to get correct pid

pid=$(cut -d' ' -f4 < /proc/self/stat)

same nice worked for sub

SUB(){
    pid=$(cut -d' ' -f4 < /proc/self/stat)
    echo "$$ != $pid"
}

echo "pid = $$"

(SUB)

check output

pid = 8099
8099 != 8100

If you were asking how to get the PID of a known command it would resemble something like this:

If you had issued the command below #The command issued was ***

dd if=/dev/diskx of=/dev/disky


Then you would use:

PIDs=$(ps | grep dd | grep if | cut -b 1-5)

What happens here is it pipes all needed unique characters to a field and that field can be echoed using

echo $PIDs


if you want a simple shell script for getting the maximum PID with variable, do this

pid=$(cat /proc/sys/kernel/pid_max)
echo $pid

that will print you the maximum PID can be.