ControlProcessLauncher.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Configuration;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Net.Http;
  6. using System.Threading;
  7. namespace ivf_tl_Operate.Helpers
  8. {
  9. /// <summary>
  10. /// operate 侧:确保 control 独立进程在运行。
  11. /// 探 /ping → 不在则 Process.Start 拉起 control.exe(命令行传账号)→ 轮询就绪。
  12. /// operate 是管理员、control 也是 requireAdministrator,拉起不再弹 UAC。
  13. /// </summary>
  14. public static class ControlProcessLauncher
  15. {
  16. private static readonly HttpClient _http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) };
  17. public static int Port =>
  18. int.TryParse(ConfigurationManager.AppSettings["controlPort"], out var p) ? p : 38080;
  19. /// <summary>探活:control 的 /ping 是否可达。</summary>
  20. public static bool IsControlAlive()
  21. {
  22. try
  23. {
  24. var resp = _http.GetAsync($"http://127.0.0.1:{Port}/ping").GetAwaiter().GetResult();
  25. return resp.IsSuccessStatusCode;
  26. }
  27. catch { return false; }
  28. }
  29. /// <summary>
  30. /// 确保 control 在跑:已在→直接返回 true;不在→拉起并轮询就绪(最多 waitSeconds)。
  31. /// </summary>
  32. public static bool EnsureRunning(string account, string password, string cacheDisk,
  33. Action<string> log, int waitSeconds = 60)
  34. {
  35. log = log ?? (_ => { });
  36. if (IsControlAlive()) { log("control 已在运行,直接连接"); return true; }
  37. string exe = ResolveExePath();
  38. if (!File.Exists(exe)) { log("找不到 control.exe:" + exe); return false; }
  39. var psi = new ProcessStartInfo
  40. {
  41. FileName = exe,
  42. Arguments = $"--account={account} --password={password} --cacheDisk={cacheDisk} --port={Port}",
  43. UseShellExecute = true, // requireAdministrator 进程需 ShellExecute 提权启动
  44. WindowStyle = ProcessWindowStyle.Hidden
  45. };
  46. try { Process.Start(psi); }
  47. catch (Exception ex) { log("拉起 control 失败:" + ex.Message); return false; }
  48. log("已拉起 control.exe,等待就绪…");
  49. for (int i = 0; i < waitSeconds; i++)
  50. {
  51. Thread.Sleep(1000);
  52. if (IsControlAlive()) { log("control 就绪"); return true; }
  53. }
  54. log("control 拉起后等待就绪超时");
  55. return false;
  56. }
  57. private static string ResolveExePath()
  58. {
  59. string rel = ConfigurationManager.AppSettings["controlExePath"]
  60. ?? @"control\ivf_tl_ControlHost.exe";
  61. return Path.IsPathRooted(rel)
  62. ? rel
  63. : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rel);
  64. }
  65. }
  66. }