python杀线程_Ctrl-C,即KeyboardInterrupt杀死Python中的线程

博客讨论了Python中使用Ctrl+C杀线程的问题。提到KeyboardInterrupt异常仅在主线程中引发,主线程会在子线程执行时被阻塞,导致Ctrl+C无法作用于子线程。给出示例代码,分析使用thread.join()会使程序等待线程结束,信号由主进程捕获。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1586010002-jmsa.png

I read somewhere that KeyboardInterrupt exception is only raised in the main thread in Python. I also read that the main thread is blocked while the child thread executes. So, does this mean that CTRL+C can never reach to the child thread. I tried the following code:

def main():

try:

thread = threading.Thread(target=f)

thread.start() # thread is totally blocking (e.g., while True)

thread.join()

except KeyboardInterrupt:

print "Ctrl+C pressed..."

sys.exit(1)

def f():

while True:

pass # do the actual work

In this case there is no effect of CTRL+C on the execution. It is like it is not able to listen to the signal. Am I understanding this the wrong way? Is there any other way to kill the thread using CTRL+C?

解决方案

The problem there is that you are using thread1.join(), which will cause your program to wait until that thread finishes to continue.

The signals will always be caught by the main process, because it's the one that receives the signals, it's the process that has threads.

Doing it as you show, you are basically running a 'normal' application, without thread features, as you start 1 thread and wait until it finishes to continue.

Python中,要终止或杀死父进程(进程间通信通常发生在子进程中调用父进程的`os.fork()`函数后),你需要使用`os.kill()`函数配合`os.getppid()`来获取父进程ID。以下是一个简单的例子: ```python import os import signal # 创建子进程 def child_process(): print(f"Child process PID: {os.getpid()}") # 父进程的PID parent_pid = os.getppid() # 设置信号处理程序 def handler(signum, frame): print(f"Parent sent SIGINT (Ctrl+C) to child process: {signum}") os._exit(0) # 注册信号处理器 signal.signal(signal.SIGINT, handler) # 开始执行其他操作 while True: pass # 这里替换为实际的工作循环 if __name__ == "__main__": try: # fork并进入子进程 pid = os.fork() if pid == 0: child_process() # 子进程运行 else: print(f"Parent process PID: {os.getpid()}") # 等待子进程完成 os.wait() # 发送SIGINT信号给子进程 os.kill(pid, signal.SIGINT) print("Terminated the child process") except KeyboardInterrupt: print("Parent received SIGINT (Ctrl+C), exiting.") ``` 在这个例子中,父进程注册了一个信号处理器,当收到`SIGINT`(通常由键盘中断引发)时,它会发送一个信号给子进程,使其退出。 对于线程间的交互,Python的标准库并没有直接提供杀死线程的功能,因为线程是并发执行的,不是独立的进程。如果你想停止某个线程,可以通过共享变量、事件或者锁来协调。例如,你可以创建一个标志变量,在线程开始时设置为`False`,然后在主线程中等待这个标志变为`True`再结束。 ```python import threading # 假设这是一个线程函数 def thread_function(stop_event): while not stop_event.is_set(): # 执行任务 ... # 在主线程中 stop_event = threading.Event() thread = threading.Thread(target=thread_function, args=(stop_event,)) thread.start() # 主线程需要时可以设置停止事件 stop_event.set() print("Thread terminated") ``` 在这里,`Event`对象用于同步线程,当`set()`被调用时,所有等待该事件的线程都会被唤醒并执行到下一个循环检查点,从而达到停止线程的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值