I want to get a list of all background processes running in the OS. job command does the work. But I am using C to do the task. The main problem is, how to distinguish background processes from the foreground processes using the status file in /proc/{pid}.
Background processes are processes which are members of a process group which is not the foreground process group on their controlling terminal.
The corresponding fields from /proc/PID/stat
are:
(5) pgrp %d
The process group ID of the process.
(8) tpgid %d
The ID of the foreground process group of the control‐
ling terminal of the process.
So those fields will be different for a background process. Also useful are (3) state
, (7) tty_nr
and (6) session
.
(The field numbering is 1-based)
The following will print (when run from an interactive shell with job control enabled) all the non-stopped background processes from the current session:
awk -vsid=$$ '$6==sid && $3!="T" && $5!=$8 {print $1, $2}' /proc/[0-9]*/stat
This is assuming, for simplicity's sake, that the process name (the second field, in parentheses) does not contain spaces; you'll have to handle that by first splitting the line on the parentheses, then on space.
Also notice this will also print processes started from subshells, which are not in the shell's jobs table (eg. (sleep 3600 &)
).