优化杀掉proxy进程

This commit is contained in:
zw
2025-08-28 19:51:57 +08:00
parent 76bb110857
commit 240c566456
2 changed files with 102 additions and 53 deletions

49
.idea/workspace.xml generated
View File

@@ -4,7 +4,10 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="eceeff5e-51c1-459c-a911-d21ec090a423" name="Changes" comment="ai 开始测试" /> <list default="true" id="eceeff5e-51c1-459c-a911-d21ec090a423" name="Changes" comment="ai 开始测试">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/Module/DeviceInfo.py" beforeDir="false" afterPath="$PROJECT_DIR$/Module/DeviceInfo.py" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
@@ -43,26 +46,26 @@
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<component name="PropertiesComponent"><![CDATA[{ <component name="PropertiesComponent">{
"keyToString": { &quot;keyToString&quot;: {
"ASKED_ADD_EXTERNAL_FILES": "true", &quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
"Python.123.executor": "Run", &quot;Python.123.executor&quot;: &quot;Run&quot;,
"Python.Main.executor": "Run", &quot;Python.Main.executor&quot;: &quot;Run&quot;,
"RunOnceActivity.ShowReadmeOnStart": "true", &quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
"SHARE_PROJECT_CONFIGURATION_FILES": "true", &quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
"git-widget-placeholder": "main", &quot;git-widget-placeholder&quot;: &quot;main&quot;,
"javascript.nodejs.core.library.configured.version": "22.18.0", &quot;javascript.nodejs.core.library.configured.version&quot;: &quot;22.18.0&quot;,
"javascript.nodejs.core.library.typings.version": "22.18.0", &quot;javascript.nodejs.core.library.typings.version&quot;: &quot;22.18.0&quot;,
"last_opened_file_path": "F:/company code/AI item/20250820/iOSAI", &quot;last_opened_file_path&quot;: &quot;F:/company code/AI item/20250820/iOSAI&quot;,
"node.js.detected.package.eslint": "true", &quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
"node.js.detected.package.tslint": "true", &quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
"node.js.selected.package.eslint": "(autodetect)", &quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
"node.js.selected.package.tslint": "(autodetect)", &quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
"nodejs_package_manager_path": "npm", &quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
"settings.editor.selected.configurable": "com.gitee.ui.GiteeSettingsConfigurable", &quot;settings.editor.selected.configurable&quot;: &quot;com.gitee.ui.GiteeSettingsConfigurable&quot;,
"vue.rearranger.settings.migration": "true" &quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
} }
}]]></component> }</component>
<component name="RecentsManager"> <component name="RecentsManager">
<key name="MoveFile.RECENT_KEYS"> <key name="MoveFile.RECENT_KEYS">
<recent name="E:\Code\python\iOSAI\resources" /> <recent name="E:\Code\python\iOSAI\resources" />
@@ -162,7 +165,9 @@
<workItem from="1756184656258" duration="24292000" /> <workItem from="1756184656258" duration="24292000" />
<workItem from="1756271781908" duration="26153000" /> <workItem from="1756271781908" duration="26153000" />
<workItem from="1756303414374" duration="1018000" /> <workItem from="1756303414374" duration="1018000" />
<workItem from="1756361418986" duration="7351000" /> <workItem from="1756361418986" duration="7579000" />
<workItem from="1756370074173" duration="5000" />
<workItem from="1756370506697" duration="4402000" />
</task> </task>
<task id="LOCAL-00001" summary="ai 开始测试"> <task id="LOCAL-00001" summary="ai 开始测试">
<option name="closed" value="true" /> <option name="closed" value="true" />
@@ -187,7 +192,7 @@
<option name="LAST_COMMIT_MESSAGE" value="ai 开始测试" /> <option name="LAST_COMMIT_MESSAGE" value="ai 开始测试" />
</component> </component>
<component name="com.intellij.coverage.CoverageDataManagerImpl"> <component name="com.intellij.coverage.CoverageDataManagerImpl">
<SUITE FILE_PATH="coverage/iOSAI$Main.coverage" NAME="Main Coverage Results" MODIFIED="1756366476180" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" /> <SUITE FILE_PATH="coverage/iOSAI$Main.coverage" NAME="Main Coverage Results" MODIFIED="1756378956708" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="" />
<SUITE FILE_PATH="coverage/iOSAI$123.coverage" NAME="123 覆盖结果" MODIFIED="1756300694280" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/test" /> <SUITE FILE_PATH="coverage/iOSAI$123.coverage" NAME="123 覆盖结果" MODIFIED="1756300694280" SOURCE_PROVIDER="com.intellij.coverage.DefaultCoverageFileProvider" RUNNER="coverage.py" COVERAGE_BY_TEST_ENABLED="false" COVERAGE_TRACING_ENABLED="false" WORKING_DIRECTORY="$PROJECT_DIR$/test" />
</component> </component>
</project> </project>

View File

@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
import signal
import sys import sys
import time import time
import json import json
@@ -32,6 +33,8 @@ class Deviceinfo(object):
self.deviceModelList: List[DeviceModel] = [] self.deviceModelList: List[DeviceModel] = []
# 最大可连接设备限制 # 最大可连接设备限制
self.maxDeviceCount = 6 self.maxDeviceCount = 6
# 操作锁
self._lock = threading.Lock()
# ===== iproxy一次性完成 路径定位 + 环境变量配置 + 启动器准备 ===== # ===== iproxy一次性完成 路径定位 + 环境变量配置 + 启动器准备 =====
try: try:
@@ -97,7 +100,6 @@ class Deviceinfo(object):
# 监听设备连接(死循环,内部捕获异常) # 监听设备连接(死循环,内部捕获异常)
# ---------------------------- # ----------------------------
def startDeviceListener(self): def startDeviceListener(self):
while True: while True:
try: try:
lists = Usbmux().device_list() lists = Usbmux().device_list()
@@ -106,7 +108,6 @@ class Deviceinfo(object):
LogManager.warning(f"usbmuxd 连接失败: {e}。请确认已安装 iTunes/Apple Mobile Device Support并在手机上“信任此电脑”") LogManager.warning(f"usbmuxd 连接失败: {e}。请确认已安装 iTunes/Apple Mobile Device Support并在手机上“信任此电脑”")
time.sleep(2) time.sleep(2)
continue continue
# 新接入设备 # 新接入设备
for device in lists: for device in lists:
if (device not in self.deviceArray) and (len(self.deviceArray) < self.maxDeviceCount): if (device not in self.deviceArray) and (len(self.deviceArray) < self.maxDeviceCount):
@@ -116,7 +117,6 @@ class Deviceinfo(object):
self.deviceArray.append(device) self.deviceArray.append(device)
except Exception as e: except Exception as e:
LogManager.error(f"连接设备失败 {device.udid}: {e}", device.udid) LogManager.error(f"连接设备失败 {device.udid}: {e}", device.udid)
# 拔出设备处理 # 拔出设备处理
self._removeDisconnected(lists) self._removeDisconnected(lists)
time.sleep(1) time.sleep(1)
@@ -161,44 +161,88 @@ class Deviceinfo(object):
# 5) 本地端口 -> 设备端口 的映射(投屏:本地 self.screenProxy -> 设备 9100 # 5) 本地端口 -> 设备端口 的映射(投屏:本地 self.screenProxy -> 设备 9100
target = self.relayDeviceScreenPort(identifier) target = self.relayDeviceScreenPort(identifier)
self.pidList.append({"target": target, "id": identifier}) # 加个非空判断
if target is not None:
with self._lock:
self.pidList.append({"target": target, "id": identifier})
# 安全杀死iproxy进程
def _terminate_proc(self, p: subprocess.Popen):
if not p:
return
if p.poll() is not None:
return
try:
p.terminate() # 先温柔
p.wait(timeout=3)
except Exception:
try:
if os.name == "posix":
try:
# 如果 iproxy 启动时用了 setsid这里可杀整个进程组
os.killpg(os.getpgid(p.pid), signal.SIGKILL)
except Exception:
p.kill()
else:
p.kill() # Windows 直接 kill
p.wait(timeout=2) # 一定要 wait避免僵尸
except Exception:
pass
# ---------------------------- # ----------------------------
# 处理拔出设备:发通知、关掉 iproxy、移出状态 # 处理拔出设备:发通知、关掉 iproxy、移出状态
# ---------------------------- # ----------------------------
def _removeDisconnected(self, current_list): def _removeDisconnected(self, current_list):
set1 = set(self.deviceArray) # 1) 计算“被拔出”的 UDID 集合 —— 用 UDID而不是对象做集合运算
set2 = set(current_list) try:
difference = list(set1 - set2) # 在旧集合中但不在新集合中 -> 已拔出 prev_udids = {getattr(d, "udid", None) for d in self.deviceArray if getattr(d, "udid", None)}
now_udids = {getattr(d, "udid", None) for d in current_list if getattr(d, "udid", None)}
except Exception as e:
LogManager.error(f"收集 UDID 失败:{e}", "")
return
removed_udids = prev_udids - now_udids
if not removed_udids:
return
for i in difference: # 2) 加锁,避免多线程同时改三个列表
udid = i.udid if not hasattr(self, "_lock"):
# 1) 通知前端type = 2 self._lock = threading.RLock()
for a in list(self.deviceModelList): with self._lock:
if udid == a.deviceId: # 2.1 通知前端并清理 deviceModelList
a.type = 2 for udid in list(removed_udids):
try: for a in list(self.deviceModelList):
self.manager.send(a.toDict()) if udid == getattr(a, "deviceId", None):
except Exception as e: a.type = 2
LogManager.warning(f"发送下线事件失败:{e}", udid) try:
self.deviceModelList.remove(a) self.manager.send(a.toDict())
except Exception as e:
LogManager.warning(f"发送下线事件失败:{e}", udid)
try:
self.deviceModelList.remove(a)
except ValueError:
pass
# 2) 关掉对应的 iproxy # 2.2 关闭该 UDID 的所有 iproxy
survivors = []
for k in list(self.pidList): for k in list(self.pidList):
if udid == k["id"]: kid = k.get("id")
target = k.get("target") if kid in removed_udids:
p = k.get("target")
try: try:
if target and target.poll() is None: self._terminate_proc(p)
target.kill() except Exception as e:
except Exception: LogManager.warning(f"关闭 iproxy 异常:{e}", kid)
pass # 不再把该项放回 survivors相当于移除
self.pidList.remove(k) else:
survivors.append(k)
self.pidList = survivors
# 3) 从已连接集合中移除 # 2.3 从已连接集合中移除(按 UDID 过滤,避免对象引用不一致导致 remove 失败)
try: self.deviceArray = [d for d in self.deviceArray if getattr(d, "udid", None) not in removed_udids]
self.deviceArray.remove(i)
except Exception: # 3) 打点
pass for udid in removed_udids:
LogManager.info("设备已拔出,清理完成(下线通知 + 端口映射关闭 + 状态移除)", udid)
# ---------------------------- # ----------------------------
# 根目录与 iproxy 可执行文件定位 # 根目录与 iproxy 可执行文件定位