PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 11, 2022

[FIXED] How to read all background processes from /proc directory?

 November 11, 2022     background-process, c, linux, proc, process     No comments   

Issue

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}.


Solution

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 &)).



Answered By - user10678532
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing