H
H
HellWalk2018-05-18 10:55:07
linux
HellWalk, 2018-05-18 10:55:07

Linux: echo $$ returns wrong PID, why?

I'm making a daemon in php (the daemon starts in the screen), you need to find out the PID of the daemon directly inside the script.
On Linux, there is an echo $$ command that returns the PID of the current process.
I write in the daemon:

// Узнаем PID текущего процесса
        exec("echo $$", $pid);
        echo "PID Демона: $pid[0]\n";

I get the result:
5afe8608e0168399846602.png
But if you look at the processes through htop, then the process has a different PID:
5afe8623a3f72878774459.png
At the same time, the number displayed by echo $$ is always 1 more than the PID of the process displayed in htop
You can, of course, simply decrease the displayed number by one and work with it, but I want to understand why this is happening.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Melkij, 2018-05-18
@HellWalk

echo $$ returns the pid of the shell that exec launched. The fact that the number is next to the desired one is a coincidence.
To get the pid of your own process in php, there is a corresponding function getmypid

W
Wexter, 2018-05-18
@Wexter

Because exec runs it in a shell
5afe88973d532713241107.png

P
pfg21, 2018-05-18
@pfg21

enable htop mode t and see the children of the process ??

S
Saboteur, 2018-05-19
@saboteur_kiev

To execute "echo $$", exec starts bash, and hence $$ is the PID of the bash process.
You need:

$pid=getmypid();
echo "Process PID $pid"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question