jiyuhang 3 месяцев назад
Родитель
Сommit
f5bf8b584b

+ 9 - 0
app.py

@@ -0,0 +1,9 @@
+from app import create_app
+
+
+# 创建应用
+app = create_app()
+
+
+if __name__ == '__main__':
+    app.run(port=5000, debug=True)

+ 15 - 0
app/__init__.py

@@ -0,0 +1,15 @@
+from flask import  Flask
+
+
+def create_app():
+    app = Flask(__name__)
+
+    # 延时注册蓝图
+    register_blueprints(app)
+    return app
+
+
+def register_blueprints(app):
+    # 在此处注册app蓝图
+    from app.routes.listenpy_route import listenpy_bp
+    app.register_blueprint(listenpy_bp)  # 注册py监听蓝图

+ 0 - 0
app/algorithm/__init__.py


+ 0 - 0
app/algorithm/monitor/__init__.py


+ 180 - 0
app/algorithm/monitor/monitor_mnger.py

@@ -0,0 +1,180 @@
+import threading
+import time
+import psutil
+from .monitor_util import Monitor
+
+class MonitorManager:
+    """监控管理器,负责管理多个进程的监控任务"""
+    def __init__(self, interval:int=2):
+        self.monitor_threads = {}  # 存放监视线程
+        self.monitoring_data = {}  # 存放监视铭牌 格式为:{pid:{pid:实际数值,'is_running':True/False}},True表示正在被监测,False表示监控器销毁
+        self.monitor_lock = threading.Lock()
+        self.interval = interval # 监测间隔默认2秒
+        self.timeout = min(interval, 5) # 监测间隔默认2秒
+
+    def start_monitoring(self, pid:int, interval:int=2):
+        """开始监控指定PID的进程, 成功返回true,失败返回false"""
+        try:
+            # 检查进程是否存在
+            if not psutil.pid_exists(pid):
+                print(f'>>>start:需要监控的进程{pid}不存在!, 启动监控线程失败...')
+                return False
+
+            with self.monitor_lock:
+                # 检查是否已经监测该进程,如果是则不需要执行后续步骤
+                if str(pid) in self.monitoring_data:
+                    if self.monitoring_data[str(pid)].get('is_running', False):
+                        print(f'>>>start:进程{pid}正在被监控中...')
+                        return True
+                # 构造监视器铭牌
+                self.monitoring_data[str(pid)] = { "pid": pid, "is_running": False}
+            # 释放锁,启动监控线程
+            # should do: 异常处理
+            event = threading.Event()
+            thread = threading.Thread(target=self.__monitor_worker, args=(pid, interval, event))
+            thread.daemon = True  # 设置为守护线程
+            thread.start()
+
+            # 验证线程是否成功启动
+            # 记录是否超时
+            success = event.wait(timeout=self.timeout)  # 超时为False
+            with self.monitor_lock:
+                # 记录是否成功创建子线程
+                is_running = self.monitoring_data[str(pid)]["is_running"] # self.monitoring_data[str(pid)]["is_running"]一定存在
+            if success and is_running and thread.is_alive():  # 不超时 且 运行成功 且 线程存活
+                with self.monitor_lock:
+                    self.monitor_threads[str(pid)] = thread
+                    print(f'成功启动{pid}监控线程')
+                    return True
+            else:  # 创建失败
+                self.clear_pid(pid)  # 清理进程数据
+                print(f'启动{pid}监控线程失败')
+                return False
+        except Exception as e:
+            print(f"发生错误: {e}, 启动监控失败: {pid}")
+            self.clear_pid(pid)  # 清理进程数据
+            return False
+    def clear_all(self):
+        """清除所有进程的监控数据"""
+        for k, v in self.monitoring_data.items():
+            self.clear_pid(int(k))
+    def clear_pid(self, pid:int):
+        """清除指定进程的监控数据"""
+        with self.monitor_lock:
+            if str(pid) in self.monitoring_data:  # 清理铭牌
+                self.monitoring_data[str(pid)]["is_running"] = False
+                # del self.monitoring_data[str(pid)]  #  不再删除这个bool监控,防止子线程在is_running生命周期外访问
+                print(f'>>>clear_id:设置is_running为False,{str(pid)}监控铭牌清理完成...')
+            if str(pid) in self.monitor_threads:  # 清理子线程worker
+                del self.monitor_threads[str(pid)]
+                print(f'>>>clear_id:清理{str(pid)}worker完成...')
+        print(f'>>>clear_id:已清理PID {pid}的监控数据')
+    def stop_monitoring(self, pid:int):
+        """停止线程监测"""
+        with self.monitor_lock:
+            # pid是否存在
+            is_exiting = str(pid) in self.monitoring_data
+            is_running = self.monitoring_data[str(pid)].get('is_running', False) if is_exiting else False
+        if is_exiting and is_running:
+            self.monitoring_data[str(pid)]["is_running"] = False
+            print(f'>>>stop:进程{pid}监控器已经停止')
+            self.clear_pid(pid)
+            return True
+        else:
+            print(f'>>>stop:进程{pid}尚未监测,停止失败,is_exiting:{is_exiting}, is_running:{is_running}')
+            return  False
+
+
+
+    def __monitor_worker(self, pid:int, interval:int, event):
+        """监控工作线程"""
+        # 在子线程中创建监视器实例,往后只有子线程自己使用这个监视器,没有静态条件
+        monitor = Monitor(pid, interval)
+        try:
+            if monitor.process :  # 确保monitor成功附加到目标进程
+                with self.monitor_lock:
+                    if str(pid) in self.monitoring_data:
+                        # Monitor初始化成功就更改运行状态,告知主线程,子线程已启动成功
+                        self.monitoring_data[str(pid)]["is_running"] = True
+                        print(f'>>>worker:进程{pid}监控器已启动,设置is_running信号为True')
+                event.set()  # 成功时通知
+                while True:
+                    with self.monitor_lock:
+                        flag = (self.monitoring_data[str(pid)]["is_running"]) and psutil.pid_exists(pid)
+                    if flag: # 如果需要运行监视且被监视进程存在
+                        # 更新监控数据
+                        print(f'>>>worker:跟进进程{pid}')
+                        monitor.update()
+                        # 存储数据点
+                        pass
+                    else:
+                        # 如果停止监视,那么该子线程会被销毁
+                        break
+                print(f'>>>worker:监控完成, 进程{pid}监视器退出监控循环...')
+            else:
+                event.set()  # 失败时通知
+                print(f'>>>worker:进程{pid}监视器创建失败, 退出监控循环...')
+
+        except Exception as e:
+            event.set()  # 异常时通知
+            print(f">>>worker: 监控PID {pid} 时发生错误: {str(e)}")
+        # worker里面不清理主线程资源
+
+
+    def search_pid(self, pid:int):
+        """搜索pid是否正在被监测,搜索到就代表正在被监测,返回True,反之亦然"""
+        with self.monitor_lock:
+            is_exiting =  str(pid) in self.monitoring_data
+            is_running = self.monitoring_data.get(str(pid), False) if is_exiting else False
+        return is_exiting and is_running  # 存在且正在运行才认为搜索成功
+
+    def get_monitoring_data(self):
+        """获取所有正在被监控的进程数据"""
+        with self.monitor_lock:
+            monitoring_data = self.monitoring_data
+        # 我们只返回正在被监控的进程id
+        query_data = {}
+        for k, v in monitoring_data.items():
+            if v["is_running"]:
+                query_data[k] = v
+        return query_data
+
+    def shutdown_all_monitoring(self):
+        """停止监测所有进程"""
+        try:
+            self.clear_all()
+            print("已停止所有进程的监控")
+            return True
+        except Exception as e:
+            print(f"停止所有进程时发生错误: {e}")
+            return False
+
+
+# 创建监控管理器实例,在线监控
+monitor_manager = MonitorManager()
+
+if __name__ == "__main__":
+    # 启动一个进程进行测试
+    import subprocess
+    process = subprocess.Popen(["python", "subtask.py"])
+    print(f"启动测试子进程 PID: {process.pid}")
+    time.sleep(2)
+    print("启动成功...")
+    # 启动进程的监控
+    print("开始监控...")
+    result = monitor_manager.start_monitoring(process.pid)
+    print(result)
+    print("正在监控...")
+    time.sleep(2)
+    # 停止进程的监控
+    print("停止监控...")
+    result = monitor_manager.stop_monitoring(process.pid)
+    print(result)
+    time.sleep(2)
+    print("监控结束...")
+
+    # 回收孤儿
+    process.terminate()  # 发送终止信号
+    time.sleep(2)
+    process.kill()  # 强制终止
+    time.sleep(2)

+ 52 - 36
monitor_util.py → app/algorithm/monitor/monitor_util.py

@@ -8,31 +8,16 @@ from numba import cuda
 import numpy as np
 import pynvml
 class Monitor:
-    def __init__(self, pid:int, alias:str=''):
+    def __init__(self, pid:int, interval=2, alias:str=''):
         self.cuda_tensor = cuda.to_device(np.arange(10000).astype(np.float32))
         self.pid = pid
+        self.interval = interval  # 相邻两次采样间隔,默认2秒
         self.process = None
         self.curr_disk_io_counter = None  # 磁盘读写计数器
-        self.curr_system_net_io_counter = psutil.net_io_counters()  # 系统网络读写计数器
+        self.curr_system_net_io_counter = None  # 系统网络读写计数器
         self.data_points=[] # 数据点
         self.max_count = 1
-        self.usage = {
-            "pid":'',            # 进程名称
-            "now_time":'',       # 当前时间
-            "cpu_pct": '',       # cpu使用率
-            "rss":'',            # 物理内存
-            "vms":'',            # 虚拟内存
-            "mem_pct":'',        # 内存使用率
-            "disk_read": '',     # 磁盘读速率
-            "disk_write": '',    # 磁盘写速率
-            "sys_net_recv": '',  # 系统网络下载速率
-            "sys_net_send": '',  # 系统网络上传速率
-            "name": '',          # 进程名称
-            "status": '',        # 进程状态
-            "pwd":'',            # 当前工作目录
-            "exe":'',            # 可执行文件路径
-            "start_time": '',    # 进程启动时间
-        }
+        self.usage = self.__init_usage
         self.usage_map = {
             "pid": '进程名称',
             "now_time": '当前时间',
@@ -53,19 +38,44 @@ class Monitor:
 
         try:
             self.process = psutil.Process(pid)
-            self.curr_disk_io_counter = self.process.io_counters()
-
+            self.curr_disk_io_counter = self.process.io_counters()  # 磁盘读写计数器
+            self.curr_system_net_io_counter = psutil.net_io_counters()  # 系统网络读写计数器
+        except (psutil.NoSuchProcess, psutil.AccessDenied):
+            print(f"未找到PID为 {pid} 的进程或无权限访问该进程。")
+            self.process = None
+        except Exception as e:
+            print(f"初始化{pid}Monitor时发生错误: {e}")
+            self.process = None
+        if self.process:
             print(f"成功附加到进程: {self.process.name()} (PID: {pid})")
             self.usage["name"] = self.process.name()
             self.usage["pid"] = f'{self.process.pid}'
             self.usage["pwd"] = self.process.cwd()
             self.usage["exe"] = self.process.exe()
             self.usage["start_time"] = datetime.fromtimestamp(self.process.create_time()).strftime('%Y-%m-%d %H:%M:%S')
-        except psutil.NoSuchProcess:
-            print(f"未找到PID为 {pid} 的进程。")
-            self.process = None
 
-    def get_memory_usage_info(self):
+
+    @property
+    def __init_usage(self):
+        return {
+            "pid":'',            # 进程名称
+            "now_time":'',       # 当前时间
+            "cpu_pct": '',       # cpu使用率
+            "rss":'',            # 物理内存
+            "vms":'',            # 虚拟内存
+            "mem_pct":'',        # 内存使用率
+            "disk_read": '',     # 磁盘读速率
+            "disk_write": '',    # 磁盘写速率
+            "sys_net_recv": '',  # 系统网络下载速率
+            "sys_net_send": '',  # 系统网络上传速率
+            "name": '',          # 进程名称
+            "status": '',        # 进程状态
+            "pwd":'',            # 当前工作目录
+            "exe":'',            # 可执行文件路径
+            "start_time": '',    # 进程启动时间
+        }
+
+    def __get_memory_usage_info(self):
         """内存使用信息"""
         if not self.process:
             raise RuntimeError(f'监控程序未能找到进程:{self.pid}')
@@ -77,12 +87,12 @@ class Monitor:
         self.usage["vms"] = f'{vms_mb:.2f}MB'  # 虚拟内存
         self.usage["mem_pct"] = f'{memory_usage_percent:.2f}%'  # 占用百分比
 
-    def get_cpu_usage_info(self):
+    def __get_cpu_usage_info(self):
         # 获取CPU使用率,设置采样间隔为1秒
         cpu_usage = self.process.cpu_percent(interval=1.0)
         self.usage["cpu_pct"] = f'{cpu_usage:.2f}%'
 
-    def get_disk_io_info(self):
+    def __get_disk_io_info(self):
         """统计磁盘读写速度"""
         new_io_counter = self.process.io_counters()
         read_bytes_diff = (new_io_counter.read_bytes - self.curr_disk_io_counter.read_bytes) / (1024 ** 2)
@@ -97,7 +107,7 @@ class Monitor:
         self.usage['disk_write'] = f'{write_speed_mB:.2f} MB/s'
         self.curr_disk_io_counter = new_io_counter
 
-    def get_net_io_info(self):
+    def __get_net_io_info(self):
         """统计网络上下行速度"""
         new_net_io_counter = psutil.net_io_counters()
         sent_bytes_mB = (new_net_io_counter.bytes_sent - self.curr_system_net_io_counter.bytes_sent) / (1024 ** 2)
@@ -111,7 +121,7 @@ class Monitor:
         self.usage['sys_net_recv'] = f'{sys_net_recv_speed:.2f} MB/s'
         self.curr_system_net_io_counter = new_net_io_counter
 
-    def get_gpu_usage_info(self):
+    def __get_gpu_usage_info(self):
         try:
             # 验证进程是否存在
             if not psutil.pid_exists(self.pid): 
@@ -147,7 +157,7 @@ class Monitor:
                         # self.usage[device_id+'rate_mem'] = gpu_util.memory if gpu_util else 0
                         self.usage[device_id+'temperature'] = temperature
                         self.usage[device_id+'power'] = power_watts
-                        # print(f"GPU {i}:")
+                        print(f"GPU {i}:")
                         # print(f"  内存使用: {memory_mb:.2f} MB")
                         # print(f"  GPU 利用率: {gpu_util.gpu if gpu_util else 0}%")
                         # print(f"  内存利用率: {gpu_util.memory if gpu_util else 0}%")
@@ -162,18 +172,25 @@ class Monitor:
             import traceback
             traceback.print_exc()
     def update(self, output_file=None):
+        """更新进程信息"""
+        # 时间间隔
+        time.sleep(self.interval)
+        # 初始化记录
+        self.usage = self.__init_usage
+        # 刷新时间
         self.usage['now_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         self.usage['status'] = self.process.status()
         # 刷新内存使用情况
-        self.get_memory_usage_info()
+        self.__get_memory_usage_info()
         # 刷新cpu使用情况
-        self.get_cpu_usage_info()
+        self.__get_cpu_usage_info()
         # 刷新硬盘读取情况
-        self.get_disk_io_info()
+        self.__get_disk_io_info()
         # 刷新网络上下行情况
-        self.get_net_io_info()
+        self.__get_net_io_info()
         # 获取GPU使用情况
-        self.get_gpu_usage_info()
+        self.__get_gpu_usage_info()
+        print(self.usage)
         if output_file:
             self.data_points.append(self.usage.copy())
             if len(self.data_points) >= self.max_count:  # 如果达到100个数据点,则保存到CSV文件中,并清空数据点
@@ -197,7 +214,6 @@ class Monitor:
                     with self.process.oneshot():
                         self.update(output_file=output_file)
                         print(self.usage)
-                        time.sleep(interval)
                 except Exception as e:
                     break
 def main():

+ 82 - 0
app/controllers/listenpy_controller.py

@@ -0,0 +1,82 @@
+from flask import jsonify
+from app.services.listenpy_service import listenpy_service
+
+class ListenPyController:
+    # 业务逻辑,需要返回明确的响应
+    def __init__(self):
+        pass
+
+    def check_pid_param(self, pid:str):
+        if not pid.isdigit():
+            return False
+        return True
+
+    def monitor_py_process(self, pid:str):
+        """
+        通过pid监听python进程
+        """
+        # 业务逻辑
+        # 检查参数类型
+        if not self.check_pid_param(pid):
+            jsonify({"status": "error", "message": "请提供有效的pid参数,参数应填写为纯数字."})
+        # 拿到pid
+        pid = int(pid)
+        # 检查pid进程是否已经添加到监测任务中,如果是就返回响应,不做后续处理
+        if listenpy_service.is_monitoring(pid):
+            return jsonify({"status": "error", "message": f"PID {pid} 已经被添加到监测列表中"})
+        # 开始尝试监听
+        if listenpy_service.start_monitoring(pid):
+            # 成功返回响应
+            return jsonify({"status": "success", "message": f"开始监听PID {pid}"})
+        else:
+            # 失败返回响应
+            return jsonify({"status": "error", "message": f"监听PID {pid} 失败"})
+
+    def stop_py_process(self, pid:str):
+        """
+        停止python进程监听
+        """
+        # 检查参数类型
+        if not self.check_pid_param(pid):
+            return jsonify({"status": "error", "message": "请提供有效的pid参数,参数应填写为纯数字."})
+        # 拿到pid
+        pid = int(pid)
+        # 如果输入的pid没有被监听,那么就返回失败响应,不做后续处理
+        if not listenpy_service.is_monitoring(pid):
+            return jsonify({"status": "error", "message": f"PID {pid} 未被添加到监测列表中"})
+        # 尝试停止监听
+        if listenpy_service.stop_monitoring(pid):
+            return jsonify({"status": "success", "message": f"停止监听PID {pid}"})
+        else:
+            return jsonify({"status": "error", "message": f"停止监听PID {pid} 失败"})
+
+    def get_listened_py_process_list(self):
+        """
+        查看所有正在监听的pid清单
+        """
+        # 拿到所有正在监听的pid清单
+        listened_data = listenpy_service.get_monitoring_list()
+        # 返回响应
+        if listened_data:
+            return jsonify({"status": "success", "message": "获取正在监听的pid清单成功,请查看[data]字段", "data": listened_data})
+
+        elif listened_data  is None:
+            return jsonify({"status": "error", "message": "没有被监听的进程"})
+        else:
+            return jsonify({"status": "error", "message": "获取正在监听的进程清单失败"})
+
+    def stop_all_listened(self):
+        """
+        停止所有正在监听的进程
+        """
+        stop_all_flag = listenpy_service.shutdown_all_monitoring()
+        if stop_all_flag:
+            return jsonify({"status": "success", "message": "已停止所有正在监听的进程"})
+        else:
+            return jsonify({"status": "error", "message": "停止所有正在监听的进程失败"})
+
+
+
+
+# 单例
+listenpy_controller = ListenPyController()

+ 51 - 0
app/routes/listenpy_route.py

@@ -0,0 +1,51 @@
+from flask import Blueprint, request, jsonify
+from app.controllers.listenpy_controller import listenpy_controller
+
+listenpy_bp = Blueprint('listenpy', __name__, url_prefix='/listenpy')   # 监听统一使用listen
+@listenpy_bp.route('/', methods=['GET'])
+def home():
+    info = {
+        "status": "success",
+        "message": "欢迎使用ListenPy,这是一个用于监听Python进程的API接口。接口说明:\n/start:监听某个python进程;\n/stop:停止监听某个python进程;\n/list:查看所有正在监听的python进程清单;\n/shutdown:停止所有监听。"
+    }
+    return jsonify(info)
+# 启动监听某个pid进程
+@listenpy_bp.route('/start', methods=['GET'])  # python进程监听
+def listen_py_process():
+    """
+    通过pid监听python进程
+    """
+    # 使用GET比较方便
+    pid = request.args.get('pid', type=str)
+    if pid is None:
+        return jsonify({"status": "error", "message": "请提供有效的pid字段,参数应填写[pid]."})
+    response = listenpy_controller.monitor_py_process(pid)
+    return response
+
+# 停止监听某个pid进程
+@listenpy_bp.route('/stop', methods=['GET'])
+def stop_listen_py_process():
+    """
+    停止python进程监听
+    """
+    pid = request.args.get('pid', type=str)
+    if pid is None:
+        return jsonify({"status": "error", "message": "请提供有效的pid字段,参数应填写[pid]."})
+    response = listenpy_controller.stop_py_process(pid)
+    return response
+
+# 查看所有正在监控的pid清单
+@listenpy_bp.route('/list', methods=['GET'])
+def get_listened_py_process_list():
+    """
+    查看所有正在监听的pid清单
+    """
+    return listenpy_controller.get_listened_py_process_list()
+
+# 停止所有监听
+@listenpy_bp.route('/shutdown', methods=['GET'])
+def stop_all_listened():
+    """
+    停止所有监听
+    """
+    return listenpy_controller.stop_all_listened()

+ 37 - 0
app/services/listenpy_service.py

@@ -0,0 +1,37 @@
+from app.algorithm.monitor.monitor_mnger import monitor_manager
+
+class ListenPyService:
+    # 只关心算法的输入和输出,算法具体实现,组织调用工具函数,函数的返回值不为json响应
+    def __init__(self):
+        pass
+
+    def is_monitoring(self, pid:int):
+        """检查系统的pid是否已经被添加到监测列表"""
+        return monitor_manager.search_pid(pid)
+
+    def start_monitoring(self, pid:int):
+        """开始监听指定pid的进程"""
+        return monitor_manager.start_monitoring(pid)
+    def stop_monitoring(self, pid:int):
+        """"""
+        return monitor_manager.stop_monitoring(pid)
+
+    def get_monitoring_list(self):
+        """获取正在被监听的进程清单"""
+        try:
+            monitoring_list =  monitor_manager.get_monitoring_data()
+            if monitoring_list:
+                return monitoring_list
+            else:
+                print(f"没有正在被监听的进程",monitoring_list)
+                return None
+        except Exception as e:
+            print(f"获取正在被监听的进程清单失败: {e}")
+            return False
+
+    def shutdown_all_monitoring(self):
+        """清除所有进程的监控数据"""
+        return monitor_manager.shutdown_all_monitoring()
+
+# 单例
+listenpy_service = ListenPyService()

+ 0 - 85
monitor_mnger.py

@@ -1,85 +0,0 @@
-import threading
-import time
-import psutil
-from monitor_util import Monitor
-
-class MonitorManager:
-    """监控管理器,负责管理多个进程的监控任务"""
-    def __init__(self):
-        self.monitor_threads = {}  # 存放监视线程
-        self.monitoring_data = {}
-        self.monitor_lock = threading.Lock()
-
-    def start_monitoring(self, pid:int, interval:int=2):
-        """开始监控指定PID的进程"""
-        try:
-            # 检查进程是否存在
-            if not psutil.pid_exists(pid):
-                return {"status": "error", "message": f"PID {pid} 的进程不存在"}
-
-            with self.monitor_lock:
-                # 检查是否已经监测该进程
-                if str(pid) in self.monitoring_data and self.monitoring_data[str(pid)]['is_running']:
-                    return {"status": "error", "message": f"PID {pid} 已经在监控中"}
-
-                self.monitoring_data[str(pid)] = {  # 构造监视器铭牌
-                    "pid": pid,
-                    "is_running": True  # 记录监视线程是否正在运行
-                }
-
-                # 启动监控线程
-                thread = threading.Thread(target=self._monitor_worker, args=(pid, interval))
-                thread.daemon = True  # 设置为守护线程
-                thread.start()
-                self.monitor_threads[str(pid)] = thread
-                return {"status": "success", "message": f"开始监控PID {pid}"}
-
-        except Exception as e:
-            return {"status": "error", "message": f"启动监控失败: {str(e)}"}
-
-    def stop_monitoring(self, pid:int):
-        """停止线程监测"""
-        with self.monitor_lock:
-            if str(pid) not in self.monitoring_data:
-                return {"status": "error", "message": f"尚未监测该进程:{pid}"}
-
-            elif str(pid) in self.monitoring_data and self.monitoring_data[str(pid)]['is_running']:# 如果正在监测该线程
-                self.monitoring_data[pid]["is_running"] = False
-                if str(pid) in self.monitor_threads:
-                    del self.monitor_threads[str(pid)]
-                return {"status": "success", "message": f"已停止监控PID {pid}"}
-            else:
-                return {"status": "error", "message": f"PID {pid} 未在监控中"}
-
-    def _monitor_worker(self, pid:int, interval:int):
-        """监控工作线程"""
-        # 在子线程中创建监视器实例,往后只有子线程自己使用这个监视器,没有静态条件
-        monitor = Monitor(pid)
-        try:
-            if monitor.process :
-                while True:
-                    with self.monitor_lock:
-                        flag = (self.monitoring_data[str(pid)]["is_running"]) and psutil.pid_exists(pid)
-                    if flag: # 如果需要运行监视且被监视进程存在
-                        # 更新监控数据
-                        monitor.update()
-                        # 存储数据点
-                        pass
-                        time.sleep(interval)
-                    else:
-                        # 如果停止监视,那么该子线程会被销毁
-                        break
-            else:
-                print(f'进程{pid}监视器创建失败')
-
-        except Exception as e:
-            print(f"监控PID {pid} 时发生错误: {str(e)}")
-        finally:
-            # 清理资源
-            with self.monitor_lock:
-                if str(pid) in self.monitoring_data:
-                    self.monitoring_data[pid]["is_running"] = False
-
-
-# 创建监控管理器实例
-monitor_manager = MonitorManager()

+ 0 - 3
monitor_online.py

@@ -1,3 +0,0 @@
-import sys
-import os
-sys.path.append(os.path.basename(__file__))

+ 7 - 0
subtask.py

@@ -0,0 +1,7 @@
+import time
+
+t = 120
+while t > 0:
+    print(t)
+    time.sleep(1)
+    t -= 1