本文整理汇总了Python中signal.setitimer函数的典型用法代码示例。如果您正苦于以下问题:Python setitimer函数的具体用法?Python setitimer怎么用?Python setitimer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了setitimer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getch
def getch(timeout=0.1):
"""Returns single character of raw input or '' if nothing after timeout"""
def _handle_timeout(signum, frame):
raise TimeoutError()
def _getch():
try:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
except TimeoutError:
return ''
signal.signal(signal.SIGALRM, _handle_timeout)
signal.setitimer(signal.ITIMER_REAL, timeout)
try:
result = _getch()
finally:
signal.alarm(0)
return result
示例2: test_eintr_zero_timeout
def test_eintr_zero_timeout(wfs, spair):
a, b = spair
interrupt_count = [0]
def handler(sig, frame):
assert sig == signal.SIGALRM
interrupt_count[0] += 1
old_handler = signal.signal(signal.SIGALRM, handler)
try:
assert not wfs(a, read=True, timeout=0)
try:
# Start delivering SIGALRM 1000 times per second,
# to trigger race conditions such as
# https://github.com/urllib3/urllib3/issues/1396.
signal.setitimer(signal.ITIMER_REAL, 0.001, 0.001)
# Hammer the system call for a while to trigger the
# race.
for i in range(100000):
wfs(a, read=True, timeout=0)
finally:
# Stop delivering SIGALRM
signal.setitimer(signal.ITIMER_REAL, 0)
finally:
signal.signal(signal.SIGALRM, old_handler)
assert interrupt_count[0] > 0
示例3: _reload
def _reload():
global _reload_attempted
_reload_attempted = True
for fn in _reload_hooks:
fn()
if hasattr(signal, "setitimer"):
# Clear the alarm signal set by
# ioloop.set_blocking_log_threshold so it doesn't fire
# after the exec.
signal.setitimer(signal.ITIMER_REAL, 0, 0)
if sys.platform == 'win32':
# os.execv is broken on Windows and can't properly parse command line
# arguments and executable name if they contain whitespaces. subprocess
# fixes that behavior.
subprocess.Popen([sys.executable] + sys.argv)
sys.exit(0)
else:
try:
os.execv(sys.executable, [sys.executable] + sys.argv)
except OSError:
# Mac OS X versions prior to 10.6 do not support execv in
# a process that contains multiple threads. Instead of
# re-executing in the current process, start a new one
# and cause the current process to exit. This isn't
# ideal since the new process is detached from the parent
# terminal and thus cannot easily be killed with ctrl-C,
# but it's better than not being able to autoreload at
# all.
# Unfortunately the errno returned in this case does not
# appear to be consistent, so we can't easily check for
# this error specifically.
os.spawnv(os.P_NOWAIT, sys.executable,
[sys.executable] + sys.argv)
sys.exit(0)
示例4: handler
def handler(signum=None, frame=None):
if len(times) < N:
times.append(time.perf_counter())
# 1 µs is the smallest possible timer interval,
# we want to measure what the concrete duration
# will be on this platform
signal.setitimer(signal.ITIMER_REAL, 1e-6)
示例5: test_stress_delivery_simultaneous
def test_stress_delivery_simultaneous(self):
"""
This test uses simultaneous signal handlers.
"""
N = self.decide_itimer_count()
sigs = []
def handler(signum, frame):
sigs.append(signum)
self.setsig(signal.SIGUSR1, handler)
self.setsig(signal.SIGALRM, handler) # for ITIMER_REAL
expected_sigs = 0
deadline = time.monotonic() + 15.0
while expected_sigs < N:
# Hopefully the SIGALRM will be received somewhere during
# initial processing of SIGUSR1.
signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5)
os.kill(os.getpid(), signal.SIGUSR1)
expected_sigs += 2
# Wait for handlers to run to avoid signal coalescing
while len(sigs) < expected_sigs and time.monotonic() < deadline:
time.sleep(1e-5)
# All ITIMER_REAL signals should have been delivered to the
# Python handler
self.assertEqual(len(sigs), N, "Some signals were lost")
示例6: main
def main():
pipe_r, pipe_w = os.pipe()
flags = fcntl.fcntl(pipe_w, fcntl.F_GETFL, 0)
flags = flags | os.O_NONBLOCK
fcntl.fcntl(pipe_w, fcntl.F_SETFL, flags)
signal.signal(signal.SIGCHLD, lambda x,y: None)
signal.signal(signal.SIGALRM, lambda x,y: None)
signal.siginterrupt(signal.SIGCHLD,False) #makes no difference
signal.siginterrupt(signal.SIGALRM,False) #makes no difference
signal.set_wakeup_fd(pipe_w)
signal.setitimer(signal.ITIMER_REAL, 2, 2)
poller = select.epoll()
poller.register(pipe_r, select.EPOLLIN)
poller.register(sys.stdin, select.EPOLLIN)
print "Main screen turn on"
while True:
events=[]
try:
events = poller.poll()
try:
for fd, flags in events:
ch=os.read(fd, 1)
if fd==pipe_r:
sys.stdout.write( "We get Signal" )
if fd==sys.stdin.fileno():
sys.stdout.write( ch )
sys.stdout.flush()
except IOError as e:
print "exception loop" + str(e)
except IOError as e:
print "exception poll" + str(e)
示例7: _send
def _send(self, command, retries=5, timeout=100):
fd = self._fd
if len(command) != 33:
raise ValueError("command must be 33 bytes long")
handler = signal.signal(signal.SIGALRM, _TimeoutError.timeout)
for attempt in range(retries):
signal.setitimer(signal.ITIMER_REAL, timeout/1000.0)
try:
if LOG.isEnabledFor(logging.DEBUG):
LOG.debug("Write: {}", hexlify(command[1:]))
fd.write(command)
fd.flush()
reply = bytearray(fd.read(32))
if LOG.isEnabledFor(logging.DEBUG):
LOG.debug("Recv: {}", hexlify(reply))
signal.setitimer(signal.ITIMER_REAL, 0)
if reply[0] != command[1]:
msg = "Expected msg type {} but got {}"
raise IOError(msg.format(command[1], reply[0]))
return reply[1:]
except _TimeoutError:
print("IO timed out, try #%d." % attempt)
# time.sleep(0.000001)
finally:
signal.signal(signal.SIGALRM, handler)
msg = "Gving up on PlasmaTrim {}"
raise IOError(msg.format(self))
示例8: open
def open(name, inittime):
#extend the commond on the condition of the type of the program
execmd = "";
if (name[-1] == "y"):
execmd = "python " + name;
if (name[-1] == "e"):
execmd = "./" + name;
if (name[-1] == 's'):
execmd = "java " + name;
#try to init the popen of the program
try:
p = subprocess.Popen(execmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = False);
except:
print "init can't find program"
return None;
#try to run the program if timeout colose the program
success = True;
try:
signal.signal(signal.SIGALRM, open);
signal.setitimer(signal.ITIMER_REAL, inittime);
p.stdout.readline(),
print "init success"
except:
success = False;
print "init timeout"
finally:
signal.setitimer(signal.ITIMER_REAL, 0);
if (success == False):
p.kill();
return None;
else:
return p;
示例9: run
def run(self):
"""When the consumer is ready to start running, kick off all of our
consumer consumers and then loop while we process messages.
"""
self.set_state(self.STATE_ACTIVE)
self.setup_consumers()
# Set the SIGCHLD handler for child creation errors
signal.signal(signal.SIGCHLD, self.on_sigchld)
# Set the SIGALRM handler for poll interval
signal.signal(signal.SIGALRM, self.on_timer)
# Kick off the poll timer
signal.setitimer(signal.ITIMER_REAL, self.poll_interval, 0)
# Loop for the lifetime of the app, pausing for a signal to pop up
while self.is_running:
if not self.is_sleeping:
self.set_state(self.STATE_SLEEPING)
signal.pause()
# Note we're exiting run
LOGGER.info('Exiting Master Control Program')
示例10: stop
def stop(self):
"""Shutdown the MCP and child processes cleanly"""
LOGGER.info('Shutting down controller')
self.set_state(self.STATE_STOP_REQUESTED)
# Clear out the timer
signal.setitimer(signal.ITIMER_PROF, 0, 0)
self._mcp.stop_processes()
if self._mcp.is_running:
LOGGER.info('Waiting up to 3 seconds for MCP to shut things down')
signal.setitimer(signal.ITIMER_REAL, 3, 0)
signal.pause()
LOGGER.info('Post pause')
# Force MCP to stop
if self._mcp.is_running:
LOGGER.warning('MCP is taking too long, requesting process kills')
self._mcp.stop_processes()
del self._mcp
else:
LOGGER.info('MCP exited cleanly')
# Change our state
self._stopped()
LOGGER.info('Shutdown complete')
示例11: read
def read(judge):
nextstep = judge.nextstep;
p = judge.popen[nextstep];
#test if the program is inited succefully
if (p == None):
print "read: can't find program reading stop"
return None;
if (judge.info[nextstep] == None):
info = "";
else:
info = judge.info[nextstep];
success = True;
print info
#try communicate with the program
try:
signal.signal(signal.SIGALRM, read);
signal.setitimer(signal.ITIMER_REAL, judge.runtime);
p.stdin.write(info);
p.stdin.flush();
s = p.stdout.readline(),
print "read: success"
except:
success = False;
print "read: timeout try:",
finally:
signal.setitimer(signal.ITIMER_REAL, 0);
#if the program can't return an answer
#the program will be killed and restarted
if (success == False):
p.kill();
judge.popen[nextstep] = open(judge.name[nextstep], judge.inittime);
return None;
return s;
示例12: setup_reporter
def setup_reporter(processor, arguments):
if arguments['--no-follow']:
return
global LOGGING_SAMPLES
if LOGGING_SAMPLES is None:
scr = curses.initscr()
atexit.register(curses.endwin)
def print_report(sig, frame):
global LOGGING_SAMPLES
output = processor.report()
if LOGGING_SAMPLES is None:
scr.erase()
try:
scr.addstr(output)
except curses.error:
pass
scr.refresh()
else:
print(output)
LOGGING_SAMPLES -= 1
if LOGGING_SAMPLES == 0:
sys.exit(0)
signal.signal(signal.SIGALRM, print_report)
interval = float(arguments['--interval'])
signal.setitimer(signal.ITIMER_REAL, 0.1, interval)
示例13: start
def start(self):
'start sampling interrupts'
if self.started:
return
self.started = True
self.rollback = signal.signal(self.signal, self._resample)
signal.setitimer(self.which, 0.01 * (1 + random.random()))
示例14: run
def run(self):
ctx = zmq.Context()
sock = ctx.socket(zmq.PAIR)
sock.connect(IPC_ADDR)
# Set up interval timer with a dummy handler
signal.signal(signal.SIGALRM, self._dummyHandler)
signal.setitimer(signal.ITIMER_REAL, self.interval, self.interval)
while True:
# Wait for the timer
signal.pause()
try:
# Non-blocking recv
(comm, data) = sock.recv_multipart(flags=zmq.NOBLOCK)
except zmq.Again:
# No data ready, go back to wait for the timer
continue
# Handling command
if comm == b"say":
print("You want me to say: {}".format(data))
elif comm == b"quit":
print("Goodbye!")
break
示例15: main
def main():
global options
if os.geteuid() != 0:
sys.stderr.write("ping uses RAW SOCKETs therefore must running with root privilegies\n")
sys.exit(-1)
options = parse_options(sys.argv[1:])
signal.signal(signal.SIGALRM, signanl_handler)
try:
sockfd = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
sockfd.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, True)
sockfd_r = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
options.sockfd = sockfd
options.packet_id = os.getpid() % 0xFFFFFF
options.destination = socket.gethostbyname(options.destination)
options.sequence_number = 0
print("PING %s, interval %d, packed identifier %d" % (options.destination, options.i, options.packet_id))
signal.setitimer(signal.ITIMER_REAL, options.i, options.i)
while True:
receive_ip_packet(sockfd_r, options.packet_id)
except socket.error as e:
sys.stderr.write("Exception: " + e.strerror + '\n')