Off-Topic > Off-Topic - Tiny Core Lounge
how to tell if PID is running in foreground or background
GNUser:
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?
Rich:
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:
--- Code: ---[ $PID == `cat /proc/$PID/stat | cut -d ' ' -f8` ]
--- End code ---
appears to work.
Running the following:
--- Code: ---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:~$
--- End code ---
20712 is a copy of mc running in the foreground. 20698 is a program I'm working on running in the background.
GNUser:
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. ;))
GNUser:
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
Rich:
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:
--- Code: ---if(pp->pgrp == pp->tpgid) outbuf[end++] = '+'; // in foreground process group
--- End code ---
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:
--- Code: ---[ `cat /proc/$PID/stat | cut -d ' ' -f5` == `cat /proc/$PID/stat | cut -d ' ' -f8` ]
--- End code ---
Which returns 0 for foreground and 1 for background.
Navigation
[0] Message Index
[#] Next page
Go to full version