/// <summary> /// 执行一段命令 /// </summary> /// <param name="command">命令</param> /// <param name="user">用户类型</param> /// <param name="suCheck">当root执行时,检测su是否存在并根据情况抛出异常</param> /// <returns></returns> public AdvanceOutput Execute(string command, LinuxUser user = LinuxUser.Normal, bool suCheck = true) { lock (exeLock) { outputBuilder.Clear(); if (user == LinuxUser.Su && suCheck && !HaveSu()) { throw new DeviceHaveNoRootException(device); } string shellCommand = user == LinuxUser.Normal ? command : $"su -c \'{command}\'"; string fullCommand = $"{device.ToFullSerial()} shell \"{shellCommand} ; exit $?\""; pStartInfo.Arguments = fullCommand; using (var process = new Process()) { process.StartInfo = pStartInfo; process.OutputDataReceived += (s, e) => { OnOutputReceived(e, false); }; process.ErrorDataReceived += (s, e) => { OnOutputReceived(e, true); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); ProcessStarted?.Invoke(this, new ProcessStartedEventArgs(process.Id)); process.WaitForExit(); process.CancelErrorRead(); process.CancelOutputRead(); outputBuilder.ExitCode = process.ExitCode; } return(outputBuilder.Result); } }
/// <summary> /// 开始获取输出 /// </summary> private void BeginRead() { builder.Clear(); _isEnableRead = true; }