main.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // This Source Code Form is subject to the terms of the Mozilla Public
  2. // License, v. 2.0. If a copy of the MPL was not distributed with this
  3. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
  4. mod ipc;
  5. mod server;
  6. use crate::server::run_server;
  7. use clap::Parser;
  8. use std::process;
  9. use tokio::process::Command;
  10. use tracing::{error, info};
  11. /// 命令行参数
  12. #[derive(Parser, Debug)]
  13. #[command(author, version, about, long_about = None)]
  14. struct Args {
  15. /// 服务器监听端口
  16. #[arg(short, long, default_value_t = 12801)]
  17. port: u16,
  18. /// 用户会话启动命令
  19. #[arg(short, long)]
  20. session_command: Option<String>,
  21. /// 启动子进程命令 (父进程退出时会自动终止子进程)
  22. #[arg(short, long)]
  23. launch_command: Option<String>,
  24. }
  25. #[tokio::main]
  26. async fn main() {
  27. // 初始化日志
  28. tracing_subscriber::fmt::init();
  29. let args = Args::parse();
  30. info!("启动参数: {:?}", args);
  31. // 设置会话命令环境变量
  32. if let Some(cmd) = &args.session_command {
  33. info!("设置会话命令: {}", cmd);
  34. unsafe {
  35. std::env::set_var("SESSION_COMMAND", cmd);
  36. }
  37. } else {
  38. info!("使用默认会话命令: $SHELL");
  39. }
  40. // 启动子进程
  41. let child = if let Some(cmd) = &args.launch_command {
  42. info!("启动子进程: {}", cmd);
  43. Some(
  44. Command::new("sh")
  45. .arg("-c")
  46. .arg(cmd)
  47. .kill_on_drop(true)
  48. .spawn()
  49. .expect("启动子进程失败")
  50. )
  51. } else {
  52. None
  53. };
  54. // 启动服务器
  55. info!("启动服务器,监听端口: {}", args.port);
  56. if let Err(e) = run_server(args.port).await {
  57. error!("服务器启动失败: {}", e);
  58. process::exit(1);
  59. }
  60. // 等待子进程退出
  61. if let Some(mut child) = child {
  62. match child.wait().await {
  63. Ok(status) => {
  64. info!("子进程已退出,状态码: {}", status);
  65. process::exit(0);
  66. }
  67. Err(e) => {
  68. error!("等待子进程时出错: {}", e);
  69. process::exit(1);
  70. }
  71. }
  72. }
  73. }