Get pid in shell (bash)

I have a problem with Bash and I don't know why.
Under the shell, I type:

echo $$ ## print 2433 (echo $$) ## also print 2433 (./getpid) ## print 2602 

"getpid" is a program to get the current pid, for example:

  int main() { printf("%d", (int)getpid()); return 0; } 

What confuses me is that:

  • I think that "(command)" is a subprocess (am I right?), And I think that its pid should be different from the parent pid, but they are the same, why ...
  • When I use my program to display pid between brackets, the pid it shows is different, right?
  • Is $$ something like a macro?

Can you help me?

+136
linux bash shell pid
Jan 11 '14 at
source share
6 answers

$$ defined to return the process identifier of the parent to the subshell; from the man page in the "Special Settings" section:

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

In bash 4, you can get the process id for a child using BASHPID .

 ~ $ echo $$ 17601 ~ $ ( echo $$; echo $BASHPID ) 17601 17634 
+191
Jan 11 '14 at 15:04
source share
— -

You can use one of the following.

  • $! is the PID of the last processed process.
  • kill -0 $PID checks if it continues to work.
  • $$ is the PID of the current shell.
+76
Aug 18 '14 at 10:43 on
source share
  • Brackets refer to a subshell in Bash . Since this is only a subshell, it can have the same PID - it depends on the implementation.
  • The C program you invoke is a separate process that has its own unique PID — it does not matter if it is in a subshell or not.
  • $$ is an alias in Bash to the current PID script . See the differences between $$ and $BASHPID here , and on the right above is an additional variable $BASH_SUBSHELL , which contains the level of nesting.
+24
Jan 11 '14 at 15:02
source share

Try getppid() if you want your C program to print shell PIDs.

+4
Jan 11 '14 at 15:08
source share

If you asked how to get the PID of a well-known team, it would look something like this:

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

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




Then you will use:

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

Here, all necessary unique characters are transferred to the field, and this field can be displayed using

echo $ PIDs

+1
Jul 18 '18 at 23:15
source share

this universal way to get the right pid

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

same good job for subwoofer

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

check output

 pid = 8099 8099 != 8100 
0
Aug 23 '19 at 10:12
source share



All Articles