python实现通过复数进程互相检测防止关闭和删除

 
要使用 Python 实现通过多个进程互相检测来防止关闭和删除,可以使用 multiprocessing 模块来创建多个进程,并通过进程间通信来实现心跳检测。以下是一个简单的示例代码,展示了如何使用两个进程相互监控:
首先,创建一个共享数据结构,用于进程间通信和存储心跳信息:
import multiprocessing
import time
# 共享状态
shared_data = multiprocessing.Value('d', time.time())  
 
然后,定义进程函数,该函数会不断更新共享数据中的心跳值:
def process_function(shared_data):
    while True:
        # 模拟进程工作
        time.sleep(1)  
        # 更新心跳
        shared_data.value = time.time()  
 
接下来,创建进程并启动:
process1 = multiprocessing.Process(target=process_function, args=(shared_data,))
process1.start()
 
在主进程中,定期检查心跳。如果发现心跳超时(即另一个进程异常退出),则打印提示信息并重新创建进程:
while True:
    time.sleep(2)  
    if time.time() - shared_data.value > 3:  
        print("heartbeat lost! restarting the process.")
        process1.terminate()  
        process1.join()  
        process1 = multiprocessing.Process(target=process_function, args=(shared_data,))
        process1.start()  
 
在上述示例中,两个进程通过共享的 shared_data 进行心跳检测。主进程每隔 2 秒检查一次心跳,如果超过 3 秒没有更新(意味着另一个进程可能已经异常退出),则终止并重新启动该进程。
完整示例
import multiprocessing
import time
# 共享状态
shared_data = multiprocessing.Value('d', time.time())  
def process_function(shared_data):
    """
    进程函数,用于更新共享数据中的心跳值
    """
    while True:
        time.sleep(2)
        shared_data.value = time.time()  
if __name__ == "__main__":
    """
    主程序
    """
    process1 = multiprocessing.Process(target=process_function, args=(shared_data,))
    process1.start()
    while True:
        time.sleep(3)
        if time.time() - shared_data.value > 5:
            print("Heartbeat lost! Restarting the process.")
            process1.terminate()
            process1.join()
            process1 = multiprocessing.Process(target=process_function, args=(shared_data,))
            process1.start()
 
在这个示例中,if __name__ == "__main__": 下面的代码就是主程序。
要运行这个程序,直接运行这个 Python 脚本即可。在运行时,它会启动一个进程 process1 执行 process_function 函数,主程序会不断检测心跳是否丢失,并在丢失时重新启动进程。
 这段 Python 代码主要实现了一个多进程的心跳监测机制:
- 首先导入了 
multiprocessing和time模块。 - 创建了一个共享数据 
shared_data,其类型为双精度浮点数,并初始化为当前时间。 
在定义的 process_function 函数中:
- 这是一个在新进程中执行的函数,它会不断循环。
 - 每 2 秒更新一次 
shared_data的值为当前时间。 
在主程序部分:
- 创建了一个名为 
process1的新进程,并指定其执行process_function函数,并传递共享数据作为参数。 - 然后进入一个主循环。
 - 每 3 秒检查一次共享数据的最新值。
 - 如果当前时间与共享数据中的时间差超过 5 秒,就认为心跳丢失。
 - 终止当前进程,等待其结束。
 - 重新创建新进程并启动,以重新开始心跳监测。
 
例如,如果在某个时刻,进程 process1 由于某种原因停止更新共享数据,那么在 5 秒后,主程序会检测到并采取重新启动进程的措施,以确保心跳的持续更新。这种机制常用于需要持续监测某个进程是否正常运行的场景。
代码优化
在Python中,我们可以使用multiprocessing模块来创建多个子进程,并通过这些子进程之间的通信来实现互相检测的功能。要防止某个进程被关闭或被删除,一种方法是让每个进程不断地检查其他进程的状态,并在其他进程退出时重新启动它们。
下面这个示例,将展示如何创建两个子进程,它们会互相监控对方的存在,并在对方消失时尝试重新启动对方:
import os
import time
import multiprocessing
from multiprocessing import Process
def monitor(pid):
    while True:
        # 检查目标进程是否存在
        if not os.path.exists(f"/proc/{pid}"):
            print(f"Process {pid} is down, restarting...")
            try:
                p = Process(target=target_function)
                p.start()
            except Exception as e:
                print(f"Failed to restart process: {e}")
        time.sleep(1)  # 避免过度消耗CPU
def target_function():
    pid = os.getpid()
    print(f"Process {pid} started.")
    
    while True:
        time.sleep(1)
def main():
    # 创建两个子进程
    p1 = Process(target=target_function)
    p2 = Process(target=target_function)
    
    p1.start()
    p2.start()
    
    # 获取进程ID
    pid1 = p1.pid
    pid2 = p2.pid
    
    # 创建监控进程
    monitor_p1 = Process(target=monitor, args=(pid1,))
    monitor_p2 = Process(target=monitor, args=(pid2,))
    
    monitor_p1.start()
    monitor_p2.start()
if __name__ == "__main__":
    main()
 
解释:
- 主进程 (
main()) 启动两个子进程p1和p2。 - 子进程 (
target_function()) 无限循环运行,模拟一个不中断的任务。 - 监控进程 (
monitor()) 不断检查指定的进程是否还在运行。如果检测到进程不存在(即被杀掉或自己停止),则尝试重新启动该进程。 
请注意,这种方法并不能真正“防止”进程被操作系统或用户关闭,只能在进程意外终止后尝试恢复它。此外,这种方式可能会导致系统资源的过度消耗,特别是在处理大量进程或者频繁重启的情况下。
另外,在实际部署这种机制之前,请确保你理解其潜在的影响,并根据需要调整睡眠时间和异常处理逻辑。




![NSSCTF练习记录:[SWPUCTF 2021 新生赛]ez_caesar](https://i-blog.csdnimg.cn/direct/928af8b76e3143c8946be8e8e5d4165f.png)





![[Spring] Spring原理(SpringBoot完结)](https://i-blog.csdnimg.cn/direct/1c7cb850baa94e748c91a03f26fb0b48.png)








