Tiny Core Linux
Off-Topic => Off-Topic - Tiny Core Lounge => Topic started by: GNUser on March 12, 2020, 11:25:02 AM
-
I have a shell script that will sometimes be run from the terminal.
When it is run from the terminal, it needs to find out whether a certain PID is running in the background or in the foreground.
With GNU procps's ps that's easy because foreground processes have a + in the status column.
Alas, BusyBox's ps has a status column but does not provide this information (it does not have the handy + symbol).
Do any of you smart TCL folks know how to determine whether a PID is running in the foreground or background, using only BusyBox tools?
-
Hi GNUser
The /proc file system tells all:
http://man7.org/linux/man-pages/man5/proc.5.html
Field number 8 in the stat file identifies the foreground process group .....
Using this type of test:
[ $PID == `cat /proc/$PID/stat | cut -d ' ' -f8` ]
appears to work.
Running the following:
tc@E310:~$ [ 20712 == `cat /proc/20712/stat | cut -d ' ' -f8` ]
tc@E310:~$ echo $?
0
tc@E310:~$ [ 20698 == `cat /proc/20698/stat | cut -d ' ' -f8` ]
tc@E310:~$ echo $?
1
tc@E310:~$
20712 is a copy of mc running in the foreground. 20698 is a program I'm working on running in the background.
-
Wow, Rich. That's beautiful.
Here's another one: Is there a generic way to find out if a certain PID is a virtual terminal (e.g., aterm, xterm, urxvt, mate-terminal, etc.)?
(I'm putting together something very special and these are the last missing pieces. I'll share it with you guys in a separate thread. ;))
-
P.S. Never mind this second question. I discovered [ -t 1 ] which is close enough for what I need.
https://unix.stackexchange.com/questions/515778/how-does-a-program-know-if-stdout-is-connected-to-a-terminal-or-a-pipe
-
Hi GNUser
I just took a look at the procps source code:
https://gitlab.com/procps-ng/procps/-/blob/master/ps/output.c
and line number 817 states:
if(pp->pgrp == pp->tpgid) outbuf[end++] = '+'; // in foreground process group
Which means they are comparing the process group ID (field number 5), not the PID to field number 8.
So the proper test should probably look like this:
[ `cat /proc/$PID/stat | cut -d ' ' -f5` == `cat /proc/$PID/stat | cut -d ' ' -f8` ]
Which returns 0 for foreground and 1 for background.
-
That does seem more correct.
However, I tested what you suggested before several times and it works as intended.
I guess when a process is the process group leader, its PID will be the same as the process group ID.
-
Hi GNUser
Since it appears that a PID and a process group ID don't have to match, I felt I should correct my answer. After all, someone
may come across this at a later date, and that distinction may be important to them.