I have a python script that is using the SIGSTOP and .SIGCONT commands with os.kill to pause or resume a process. Is there a way to determine whether the related PID is in the paused or resumed state?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can find information about a process from its /proc directory (/proc/<PID>
). Specifically, you can find its run state with this python expression:
open(os.path.join('/proc', str(pid), 'stat')).readline().split()[2]=='T'
EDIT: This next expression fixes a (presumably rare) bug with the original:
re.sub(r'\(.*\)', '()', open(os.path.join('/proc', str(pid), 'stat')).readline()).split()[2]=='T'
回答2:
call ps and check the STAT value. D Uninterruptible sleep (usually IO) R Running or runnable (on run queue) S Interruptible sleep (waiting for an event to complete) T Stopped, either by a job control signal or because it is being traced. W paging (not valid since the 2.6.xx kernel) X dead (should never be seen) Z Defunct ("zombie") process, terminated but not reaped by its parent.
回答3:
You can use psutil:
>>> import psutil
>>> pid = 1243
>>> p = psutil.Process(pid)
>>> p.status
0
>>> str(p.status)
'running'
>>> p.status == psutil.STATUS_RUNNING
True
>>>
>>> p.suspend()
>>> p.status
3
>>> str(p.status)
'stopped'
>>> p.status == psutil.STATUS_STOPPED
True
>>>
>>> p.resume()
>>> str(p.status)
'running'
>>>