Fix race condition in ps.top

When a process ends between the start of the function and the end, a
psutil.NoSuchProcess exception will be raised if you try to invoke
member functions of a psutil.Process object for that PID.
This commit is contained in:
Erik Johnson 2020-04-28 10:58:58 -05:00 committed by Daniel Wozniak
parent 92fc17115b
commit 0db615b40b

View file

@ -178,10 +178,16 @@ def top(num_processes=5, interval=3):
"cpu": {},
"mem": {},
}
for key, value in six.iteritems(process.cpu_times()._asdict()):
info["cpu"][key] = value
for key, value in six.iteritems(process.memory_info()._asdict()):
info["mem"][key] = value
try:
for key, value in six.iteritems(process.cpu_times()._asdict()):
info["cpu"][key] = value
for key, value in six.iteritems(process.memory_info()._asdict()):
info["mem"][key] = value
except psutil.NoSuchProcess:
# Process ended since psutil.pids() was run earlier in this
# function. Ignore this process and do not include this process in
# the return data.
continue
result.append(info)
return result