You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为所有运行中应用添加监听器以实时更新运行应用列表?

嘿,我刚好碰到过类似的需求,来给你捋捋怎么解决这个实时同步运行中应用列表的问题!

问题根源先搞清楚

你当前的实现应该是一次性扫描系统进程来生成应用列表,这本质是个静态快照——只能拿到调用函数那一瞬间的运行状态,自然没法追踪之后新启动的应用。要实现动态同步,核心是要订阅系统的进程创建事件,让新进程一启动就自动触发逻辑更新你的数组。

分平台给你具体实现思路

不同操作系统的进程监听机制不一样,我分别给你举Python的示例(易上手,跨平台适配性也不错):

Windows平台:用WMI监听进程启动事件

Windows的WMI(Windows管理规范)提供了原生的进程事件订阅能力,能实时捕获新进程创建的动作:

import wmi
import threading

# 用集合存应用名,自动去重
running_apps = set()

def init_running_apps():
    """初始化当前已运行的应用列表"""
    c = wmi.WMI()
    for process in c.Win32_Process():
        app_name = process.ProcessName
        # 过滤出exe格式的应用(可根据需求调整)
        if app_name.endswith(".exe"):
            running_apps.add(app_name)
    print("初始运行应用列表:", running_apps)

def monitor_new_processes():
    """后台监听新启动的进程,自动更新列表"""
    c = wmi.WMI()
    # 订阅进程启动的创建事件
    process_watcher = c.Win32_ProcessStartTrace.watch_for("creation")
    while True:
        try:
            new_process = process_watcher()
            app_name = new_process.ProcessName
            if app_name.endswith(".exe") and app_name not in running_apps:
                running_apps.add(app_name)
                print(f"新应用已加入列表: {app_name}")
        except Exception as e:
            print(f"监听进程时出错: {e}")
            break

if __name__ == "__main__":
    init_running_apps()
    # 启动后台监听线程,不阻塞主线程
    monitor_thread = threading.Thread(target=monitor_new_processes, daemon=True)
    monitor_thread.start()
    # 保持程序运行,按回车退出
    input("按回车键停止监听...\n")

Linux/macOS平台:监听/proc目录(Linux)或FSEvents(macOS)

Linux下可以通过监听/proc目录的新PID文件夹来感知进程启动,macOS则可以用FSEvents机制,这里给你Linux的示例(用pyinotify库):

import pyinotify
import os
import threading

running_apps = set()

def init_running_apps():
    """初始化当前已运行的应用列表"""
    for pid in os.listdir("/proc"):
        if pid.isdigit():
            try:
                # 读取进程的命令名
                with open(f"/proc/{pid}/comm", "r") as f:
                    app_name = f.read().strip()
                    running_apps.add(app_name)
            except (FileNotFoundError, PermissionError):
                # 忽略已退出的进程或无权限访问的进程
                continue
    print("初始运行应用列表:", running_apps)

class ProcessCreateHandler(pyinotify.ProcessEvent):
    """处理/proc目录的新创建事件"""
    def process_IN_CREATE(self, event):
        pid = event.pathname.split("/")[-1]
        if pid.isdigit():
            try:
                with open(f"/proc/{pid}/comm", "r") as f:
                    app_name = f.read().strip()
                    if app_name not in running_apps:
                        running_apps.add(app_name)
                        print(f"新应用已加入列表: {app_name}")
            except (FileNotFoundError, PermissionError):
                pass

def monitor_new_processes():
    """启动进程监听"""
    watch_manager = pyinotify.WatchManager()
    # 只监听创建事件
    mask = pyinotify.IN_CREATE
    notifier = pyinotify.ThreadedNotifier(watch_manager, ProcessCreateHandler())
    notifier.start()
    # 监听/proc目录,不递归子目录
    watch_manager.add_watch("/proc", mask, rec=False)
    notifier.join()

if __name__ == "__main__":
    init_running_apps()
    monitor_thread = threading.Thread(target=monitor_new_processes, daemon=True)
    monitor_thread.start()
    input("按回车键停止监听...\n")

几个关键细节要注意

  • 去重处理:用set代替list存储应用名,能自动避免同一应用多次启动导致的重复条目。
  • 进程过滤:你可以根据需求加过滤逻辑,比如只保留带GUI的用户应用(Windows可以判断进程是否有窗口,Linux可以结合xwininfo工具),过滤掉系统后台进程。
  • 权限问题:监听系统进程通常需要管理员/root权限,运行时记得提升权限。
  • 资源效率:事件监听的方式比定时轮询高效得多,不会频繁扫描系统资源。

这样改完之后,新启动的应用会被实时捕获并自动加入你的列表,完全不需要重启程序或者重新调用函数~

内容的提问来源于stack exchange,提问作者dbrownjave

火山引擎 最新活动