I've googled this question, but never found anything useful for my particular case.
So, what I'm trying to figure out is the PID of a certain command that is running so I can kill it if necessary. I know it's possible to get the PID of a command by typing echo $!
So supposedly
my_command & echo $!
should give me the PID. But this isn't the case, and I think I know why: My command is as follows:
screen -d -m -S Radio /path/to/folder -f frequency -r path/to/song
which opens a detached screen
first and then types the command so that it gets executed and keeps on running in the background. This way the PID that echo
shows me is the wrong one. I'm guessing it shows me PID of screen -d -m -S Radio /path/to/folder -f frequency -r path/to/song
instead of the PID of the command run in the new terminal created by screen.
But there's another problem to it: when I run screen -ls
in the terminal, the command that is running in the background doesn't show up! I'm fairly certain it's running because the Pi is constantly at 25% CPU usage (instead of the 0% or 1% usually) and when I type ps au
I can actually see the command and the PID.
So now I'm calling the community: any idea on how I could find the PID of that certain command in the new terminal? I'm writing a bash script, so it has to be possible to obtain the PID through code. Perfect would be a command that stores the PID in a variable!
Thanks to @glennjackman I managed to get the PID I wanted with a simple pgrep search_word
. At first it wasn't working, but somehow I made it work after some trial and error. For those wanting the PID on a variable, just type
pid=$(pgrep search_word)
Regarding the problem with screen -ls
not showing my detached session, it's still not solved, but I'm not bothered with it. Thanks again for solving my problem @glennjackman !
EDIT:
Second problem solved, check the comments on berends answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With