Linux 如何从python程序发送信号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15080500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:07:35  来源:igfitidea点击:

How can I send a signal from a python program?

pythonlinuxsignals

提问by user192082107

I have this code which listens to USR1 signals

我有这个监听 USR1 信号的代码

import signal
import os
import time

def receive_signal(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)

print 'My PID is:', os.getpid()

while True:
    print 'Waiting...'
    time.sleep(3)

This works when I send signals with kill -USR1 pid

这在我发送信号时有效 kill -USR1 pid

But how can I send the same signal from within the above python script so that after 10 seconds it automatically sends USR1and also receives it , without me having to open two terminals to check it?

但是如何从上面的 python 脚本中发送相同的信号,以便在 10 秒后自动发送USR1和接收它,而不必打开两个终端来检查它?

回答by Rob?

If you are willing to catch SIGALRMinstead of SIGUSR1, try:

如果您愿意捕获SIGALRM而不是SIGUSR1,请尝试:

signal.alarm(10)

Otherwise, you'll need to start another thread:

否则,您将需要启动另一个线程:

import time, os, signal, threading
pid = os.getpid()
thread = threading.Thread(
  target=lambda: (
    time.sleep(10),
    os.kill(pid, signal.SIGUSR1)))
thread.start()

Thus, this program:

因此,这个程序:

import signal
import os
import time

def receive_signal(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)
signal.signal(signal.SIGALRM, receive_signal)  # <-- THIS LINE ADDED

print 'My PID is:', os.getpid()

signal.alarm(10)                               # <-- THIS LINE ADDED

while True:
    print 'Waiting...'
    time.sleep(3)

produces this output:

产生这个输出:

$ python /tmp/x.py 
My PID is: 3029
Waiting...
Waiting...
Waiting...
Waiting...
Received: 14
Waiting...
Waiting...

回答by moomima

You can use os.kill():

您可以使用os.kill()

os.kill(os.getpid(), signal.SIGUSR1)

Put this anywhere in your code that you want to send the signal from.

把它放在你想要发送信号的代码中的任何地方。