3

What does psutil.process_iter() include? Since, its a cached instance, does it include only processes that are running at the time or it includes everything and leaves their present status to be user verified? My code:

for _process in psutil.process_iter():
    try:
        new_proc = _process.as_dict(attrs=['cpu_times', 'name', 'pid', 'status'])
    except psutil.NoSuchProcess:
        continue

What all status gets filtered here? And what all do I have to verify on my own?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
user3432110
  • 217
  • 1
  • 5
  • 11

2 Answers2

2

psutil.process_iter() iterates over all the running processes in the system. ZombieProcess error is mostly observed in MacOS and workaround could be to handle it in the exception with except psutil.ZombieProcess:

for _process in psutil.process_iter():
    try:
        new_proc = _process.as_dict(attrs=['cpu_times', 'name', 'pid', 'status'])
    except psutil.NoSuchProcess:
        continue
    except psutil.ZombieProcess:
        continue
Parth Naik
  • 186
  • 1
  • 6
0

The docs for psutil.process_iter() say:

Return an iterator yielding a Process class instance for all running processes on the local machine. Every instance is only created once and then cached into an internal table which is updated every time an element is yielded. emphasize is mine

where "running" is defined by .is_running() method that returns True for zombie processes. .is_running() is safe to use even if the process is gone and its pid is reused.

My understanding is that _process.is_running() is true at the moment psutil.process_iter() yields it. In principle, before _process.as_dict returns with the info, several things may happen:

  1. process may die -- become a zombie: _process.is_running() is true, pid and status are meaningful
  2. it may be reaped -- dead-dead: the process info is unavailable (psutil.NoSuchProcess exception) or outdated (if cached)
  3. its pid may be reused -- some _process methods may return incorrectly the info for the new process. .is_running() uses several process attributes so it should detect the case when pid is reused.

Normally, OS doesn't reuse pid immediately therefore p.3 shouldn't occur frequently.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • That is correct. The `Process` class is bound to a process via its PID. As such, that PID can disappear at any time or be reused [1]. That is why every time you deal with it you're supposed to do it in a try/except catching at least `NoSuchProcess` exception (which also includes `ZombieProcess`). [1] it must be said that unless the `Process` instance is old the risk of incurring into PIDs being reused is very low or perhaps 0. – Giampaolo Rodolà Jun 22 '16 at 22:23