借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
3.52 KiB
XCoder
using System;
using System.ComponentModel;
using System.Diagnostics;
using NewLife;

namespace NewLife.XCoder.Services;

/// <summary>命令行执行(供语音合成、adb 等外部工具复用)</summary>
/// <remarks>
/// 只做三件事:把「可执行文件 + 参数」拆开、执行并回收输出、超时杀掉进程。
/// 失败一律抛异常(<see cref="Win32Exception"/> 表示可执行文件不存在),由调用方决定提示文案。
/// </remarks>
public static class ProcessRunner
{
    /// <summary>执行命令行并返回输出(标准输出 + 错误输出)</summary>
    /// <param name="command">命令行文本,如 <c>adb devices -l</c></param>
    /// <param name="timeoutMs">超时毫秒数,超时后强制结束进程</param>
    /// <returns>输出文本</returns>
    /// <exception cref="TimeoutException">执行超时</exception>
    /// <exception cref="Win32Exception">可执行文件不存在</exception>
    /// <exception cref="InvalidOperationException">退出码非 0</exception>
    public static String Run(String command, Int32 timeoutMs = 30000)
    {
        var (fileName, args) = SplitCommand(command);

        var info = new ProcessStartInfo(fileName)
        {
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        };

        if (!args.IsNullOrEmpty()) info.Arguments = args;

        using var process = Process.Start(info) ?? throw new InvalidOperationException($"无法启动:{fileName}");

        // 先读输出再等待,避免管道缓冲区写满导致进程卡住
        var stdout = process.StandardOutput.ReadToEndAsync();
        var stderr = process.StandardError.ReadToEndAsync();

        if (!process.WaitForExit(timeoutMs))
        {
            try { process.Kill(true); } catch { }

            throw new TimeoutException($"{fileName} 执行超时({timeoutMs}ms)");
        }

        var output = stdout.GetAwaiter().GetResult();
        var error = stderr.GetAwaiter().GetResult();

        if (process.ExitCode != 0) throw new InvalidOperationException(error.IsNullOrEmpty() ? $"退出码 {process.ExitCode}" : error.Trim());

        return error.IsNullOrEmpty() ? output : output + error;
    }

    /// <summary>尝试执行命令,失败返回 null 而不抛异常</summary>
    /// <param name="command">命令行文本</param>
    /// <param name="timeoutMs">超时毫秒数</param>
    /// <returns>输出文本;失败返回 null</returns>
    public static String? TryRun(String command, Int32 timeoutMs = 30000)
    {
        try
        {
            return Run(command, timeoutMs);
        }
        catch (Exception)
        {
            return null;
        }
    }

    /// <summary>把「可执行文件 + 参数」拆开(首个空格为界,支持带引号的路径)</summary>
    /// <param name="command">命令行文本</param>
    /// <returns>可执行文件名与参数</returns>
    public static (String fileName, String args) SplitCommand(String command)
    {
        if (command.IsNullOrWhiteSpace()) throw new ArgumentException("命令为空", nameof(command));

        var text = command.Trim();

        if (text[0] == '"')
        {
            var end = text.IndexOf('"', 1);
            if (end < 0) return (text.Trim('"'), "");

            return (text[1..end], text[(end + 1)..].Trim());
        }

        var index = text.IndexOf(' ');
        if (index < 0) return (text, "");

        return (text[..index], text[(index + 1)..].Trim());
    }
}