简体   繁体   English

为什么我的python SIGPROF不起作用?

[英]Why my python SIGPROF doesn't work?

I am installing the SIGPROF signal and execute the handler every 2 seconds. 我正在安装SIGPROF信号并每2秒执行一次处理程序。 Is there any problem? 有什么问题吗?

  1 #!/usr/bin/env python
  2 #-*-coding: utf-8 -*-
  3 #pylint: disable=W0141,W0613,W0603
  4 
  5 import os
  6 import sys
  7 import signal
  8 import time
  9 
 10 def myhandler(signum, frame):
 11     print "myhandler"
 12     sys.stdout.flush()
 13 
 14 signal.signal(signal.SIGPROF, myhandler)
 15 signal.setitimer(signal.ITIMER_PROF, 2, 2)
 16 print signal.getitimer(signal.ITIMER_PROF)
 17 
 18 while True:
 19     print "sleeping 1..."
 20     sys.stdout.flush()
 21     time.sleep(1)

Those timers only decrement when the process is executing, since it's mostly sleeping it takes very long for the timer to expire, if you remove the sleep it should work fine, from the docs : 这些计时器只在进程执行时才会减少,因为它主要是睡眠,计时器到期需要很长时间,如果你从文档中删除睡眠应该可以正常工作:

signal.ITIMER_PROF Decrements interval timer both when the process executes and when the system is executing on behalf of the process. signal.ITIMER_PROF在进程执行时以及系统代表进程执行时减少间隔计时器。 Coupled 再加

Try: 尝试:

while True:
    for i in xrange(100000):
        pass

No, it works as expected. 不,它按预期工作。 As stated by the documentation , ITIMER_PROF 文档所述 ,ITIMER_PROF

decrements interval timer both when the process executes and when the system is executing on behalf of the process. 当进程执行时以及系统代表进程执行时,减少间隔计时器。 Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. 与ITIMER_VIRTUAL结合使用,此计时器通常用于分析应用程序在用户和内核空间中花费的时间。 SIGPROF is delivered upon expiration. SIGPROF在到期时交付。

Since the sleep call causes the process to do nothing, the timer is decremented very slowly. 由于sleep调用导致进程无效,因此计时器非常缓慢地递减。 Get rid of the sleep: 摆脱困境:

#!/usr/bin/env python
#-*-coding: utf-8 -*-
#pylint: disable=W0141,W0613,W0603

import os
import sys
import signal
import time

def myhandler(signum, frame):
    print "myhandler"
    sys.stdout.flush()

signal.signal(signal.SIGPROF, myhandler)
signal.setitimer(signal.ITIMER_PROF, 2, 2)
print signal.getitimer(signal.ITIMER_PROF)

while True:
    continue

And then when it is run you can see the signal working: 然后当它运行时你可以看到信号工作:

$ python prof.py 
(2.004125, 2.000125)
myhandler
myhandler

If you want to time it in 'real' time (its not clear from the question what you're aiming to do) rather than processor time, use ITIMER_REAL and catch the SIGALRM signal instead. 如果你想在'实际'时间(从你的目标不清楚)而不是处理器时间,请使用ITIMER_REAL并捕获SIGALRM信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM