Qin Yixiao Qin Yixiao - 2 months ago 10
Linux Question

Bash script to list all processes in the foreground process group of a terminal

How can I write a bash script to print out the PIDs of all processes in the foreground process group of a given terminal (which is different from the one in which I run the script)? I know that the C function

tcgetpgrp
can do the job, but I am wondering if there exist any command line utilities that can do this more easily.

Answer

To find the pids of all processes in the foreground process group of pts/29, you can do (on linux):

ps ao stat=,pid=,tty=  | awk '$1 ~ /\+/ && $3 ~ /pts\/29/{ print $2}'

ps is often different, and I am uncertain of the portability of that solution.