I have problem with Bash, and I don't know why.
Under shell, I enter:
echo $$ ## print 2433
(echo $$) ## also print 2433
(./getpid) ## print 2602
"getpid" is a C program to get current pid, like:
int main() { printf("%d", (int)getpid()); return 0; }
What confuses me is that:
Can you help me?
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
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
$$
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.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.Source: Stackoverflow.com