private void runTask(videoTask t, Process process) { this.rsForm.setPercent("0.0"); this.rsForm.setTime(""); this.rsForm.setFps(""); this.rsForm.setEta(""); string fp = t.getFP(); process = new System.Diagnostics.Process(); process.StartInfo.FileName = "cmd"; // 必须禁用操作系统外壳程序 process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardInput = true; process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler); process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.Start(); this.PIDs[0] = process.Id; this.rsForm.PID = process.Id; this.rsForm.setStopBtnState(true); // 找到预设存储的文件并提取到taskSetting中 string tsfp = System.Windows.Forms.Application.StartupPath + "\\taskSettings\\" + t.getSetting() + ".json"; taskSetting ts = JsonConvert.DeserializeObject <taskSetting>(File.ReadAllText(tsfp)); // 将encoder信息传给信息显示界面 this.rsForm.encodingProgram = ts.encoder; this.rsForm.HideVideoEncoderSetting(); cmdCode c = new cmdCode(fp, ts, this.outputFolderPath); string cmd; int type = c.taskType(); int checkNum = 0; int beforeProcessCheckTime = 3500; int processCheckInterval = 1000; const int checkF = 20; // 定义一个内部(匿名)方法 // 整个视频转换过程结束时 InnerMethodDelagate afterSuccess = delegate() { this.finishedNum++; this.rsForm.setStatusBarFilesCountLabel(this.finishedNum, this.num); try { process.CancelErrorRead(); process.CancelOutputRead(); } catch (Exception e) { //saveLog2File(); } this.rsForm.setEta(""); this.rsForm.setFps(""); this.rsForm.setTime(""); this.rsForm.setEstKbps(""); this.rsForm.SetTaskStepsLabel(true); Process p = Process.GetProcessById(this.PIDs[0]); p.Kill(); this.rsForm.setStopBtnState(false); this.rsForm.setPercent("-3"); this.isfinished[0] = true; this.reportCount = 0; this.log.Clear(); miniLog += t.getFP() + Environment.NewLine + Environment.NewLine + Environment.NewLine; saveMiniLog2File(); }; // 运行失败时调用 InnerMethodDelagate afterFailed = delegate() { this.isfailed = true; saveLog2File(); this.rsForm.setPercent("-1"); this.rsForm.setTime("发生错误"); this.rsForm.setFps("日志保存在程序目录"); int sleepTime = 5; // 设置失败后继续下一个任务的时间 this.rsForm.setEta(sleepTime.ToString() + "秒后继续运行"); this.rsForm.setStatusBarLabelTextColorRED(); this.finishedNum++; this.rsForm.setStatusBarFilesCountLabel(this.finishedNum, this.num); this.rsForm.HideVideoEncoderSetting(); try { process.CancelErrorRead(); process.CancelOutputRead(); } catch (Exception e) { //saveLog2File(); } Thread.Sleep(sleepTime * 1000); Process p = Process.GetProcessById(this.PIDs[0]); p.Kill(); this.rsForm.setStopBtnState(false); this.rsForm.setPercent("-3"); this.isfinished[0] = true; this.reportCount = 0; this.log.Clear(); }; // 视频编码前更新UI(显示视频总帧数) InnerMethodDelagate DispVideoFrames = delegate() { // MediaInfo读取视频帧数 MediaInfo MI = new MediaInfo(); string duration; string frameRate; string frames; MI.Open(t.getFP()); duration = MI.Get(StreamKind.Video, 0, "Duration"); try { double totalTime = Double.Parse(duration) / 1000.0; frameRate = MI.Get(StreamKind.Video, 0, "FrameRate"); frames = ((int)(totalTime * Double.Parse(frameRate))).ToString(); if (!String.IsNullOrWhiteSpace(frames)) { this.rsForm.setTime("0/" + frames); } } catch (Exception e) { //saveLog2File(); } }; InnerMethodDelagate VideoEncode = delegate() { // 视频编码 this.encoding = true; this.rsForm.setPercent("0.0"); string ext = this.getFileExtName(t.getFP()); if (String.Equals(ext, "avs", StringComparison.CurrentCultureIgnoreCase)) { this.videoType = AVS; } else { this.videoType = NORMAL; DispVideoFrames(); } cmd = c.cmdCodeGenerate(VIDEOENCODE, this.videoType); process.StandardInput.WriteLine(cmd); try { process.BeginErrorReadLine(); process.BeginOutputReadLine(); } catch (Exception e) { //saveLog2File(); } checkNum = 0; this.reportCount = 0; int cpx2 = this.checkPattern + this.checkPattern; for (int i = 0; i < cpx2; i++) { checkFrame[i] = 0; } for (int i = 0; i < cpx2; i++) { this.fps[i] = 0; } Thread.Sleep(beforeProcessCheckTime); Process p; switch (videoType) { case NORMAL: p = GetSubTaskProcess(ts.encoder); if (p != null) { this.subTaskPID = p.Id; } else { this.subTaskPID = -1; } break; case AVS: Process avsP = GetSubTaskProcess("avs4x265.exe"); int avsId = avsP.Id; if (avsP != null) { bool hasFound = false; // 等待视频编码进程启动,最长等待1小时 for (int i = 0; i < 7200; i++) { // 确认avs进程仍在运行 try { Process.GetProcessById(avsId); } catch (Exception e) { if (this.encoding == true || ConfirmFailed()) { afterFailed(); } return; } // 每隔500ms寻找视频编码进程 p = GetSubTaskProcess(ts.encoder, avsId); if (p != null) { this.subTaskPID = p.Id; hasFound = true; break; } else { Thread.Sleep(500); } } if (!hasFound) { this.subTaskPID = -1; } } else { this.subTaskPID = -1; } break; default: break; } this.rsForm.ShowVideoEncoderSetting(); while (this.encoding == true || this.postProcessing == true) { try { Process.GetProcessById(this.subTaskPID); } catch (Exception e) { if (this.encoding == true || ConfirmFailed()) { afterFailed(); } return; } Thread.Sleep(processCheckInterval); } try { process.CancelErrorRead(); process.CancelOutputRead(); } catch (Exception e) { //saveLog2File(); } this.rsForm.HideVideoEncoderSetting(); }; InnerMethodDelagate Mux = delegate() { // muxer this.muxing = true; int stepIdx = type == ONLYVIDEO ? 2 : 3; this.rsForm.SetTaskStepsLabel(false, stepIdx, stepIdx, MUXER); cmd = c.cmdCodeGenerate(MUXER); process.StandardInput.WriteLine(cmd); try { process.BeginErrorReadLine(); process.BeginOutputReadLine(); } catch (Exception e) { //saveLog2File(); } checkNum = 0; Thread.Sleep(beforeProcessCheckTime); // 有些超短的视频(1-2M),如果不加这句就会直接判定为任务已失败,疑似原因:没等判断完进程就已经结束 string muxerProcessName = ""; if (String.Equals("mp4", ts.outputFormat)) { muxerProcessName = "mp4Box"; } else if (String.Equals("mkv", ts.outputFormat)) { muxerProcessName = "mkvmerge"; } Process p = GetSubTaskProcess(muxerProcessName); if (p != null) { this.subTaskPID = p.Id; } else { this.subTaskPID = -1; } while (this.muxing == true) { try { Process.GetProcessById(this.subTaskPID); } catch (Exception e) { Thread.Sleep(1000); if (this.muxing == true) { afterFailed(); } return; } Thread.Sleep(processCheckInterval); //checkNum = checkCmdRunning(checkNum, checkF); //if (checkNum == -1) //{ // return; //} } afterSuccess(); string tempVideoFp = c.cmdCodeGenerate(DELETEVIDEOTEMP); string tempAudioFp = c.cmdCodeGenerate(DELETEAUDIOTEMP); try { File.Delete(tempVideoFp); File.Delete(tempAudioFp); } catch (System.IO.IOException ex) { this.log.AppendLine("出现异常:" + ex); saveLog2File(); } }; // 音频编码或复制开始前更新UI(显示音频总时长) InnerMethodDelagate DispAudioDuration = delegate() { // MediaInfo读取音频时长 MediaInfo MI = new MediaInfo(); string duration; MI.Open(c.getAudioSource()); duration = MI.Get(StreamKind.Audio, 0, 69); if (!String.IsNullOrWhiteSpace(duration)) { this.rsForm.setTime("0/" + duration); } this.rsForm.setPercent("0.0", AUDIOENCODE); }; InnerMethodDelagate ClearUIAfterAudioProcessing = delegate() { this.rsForm.setPercent("0.0"); this.rsForm.setTime(""); this.rsForm.setFps(""); }; switch (type) { case ONLYVIDEO: this.rsForm.SetTaskStepsLabel(false, 1, 2, VIDEOENCODE); VideoEncode(); // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1 if (isfailed) { return; } //afterSuccess(); Mux(); break; case COPYAUDIO: // 复制音频 cmd = c.cmdCodeGenerate(AUDIOCOPY); process.StandardInput.WriteLine(cmd); process.BeginErrorReadLine(); process.BeginOutputReadLine(); this.audioProcessing = true; this.rsForm.SetTaskStepsLabel(false, 1, 3, AUDIOCOPY); DispAudioDuration(); checkNum = 0; Thread.Sleep(beforeProcessCheckTime); Process p = GetSubTaskProcess("ffmpeg"); if (p != null) { this.subTaskPID = p.Id; } else { this.subTaskPID = -1; } while (this.audioProcessing == true) { try { Process.GetProcessById(this.subTaskPID); } catch (Exception e) { Thread.Sleep(1000); if (this.audioProcessing == true) { afterFailed(); } return; } Thread.Sleep(processCheckInterval); //checkNum = checkCmdRunning(checkNum, checkF); //if (checkNum == -1) //{ // return; //} } ClearUIAfterAudioProcessing(); process.CancelErrorRead(); process.CancelOutputRead(); this.rsForm.SetTaskStepsLabel(false, 2, 3, VIDEOENCODE); // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1 if (isfailed) { return; } VideoEncode(); // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1 if (isfailed) { return; } Mux(); break; case SUPPRESSAUDIO: // 音频编码 cmd = c.cmdCodeGenerate(AUDIOENCODE); process.StandardInput.WriteLine(cmd); process.BeginErrorReadLine(); process.BeginOutputReadLine(); this.audioProcessing = true; this.rsForm.SetTaskStepsLabel(false, 1, 3, AUDIOENCODE); DispAudioDuration(); checkNum = 0; Thread.Sleep(beforeProcessCheckTime); Process p2 = GetSubTaskProcess(ts.audioEncoder); if (p2 != null) { this.subTaskPID = p2.Id; } else { this.subTaskPID = -1; } while (this.audioProcessing == true) { try { Process.GetProcessById(this.subTaskPID); } catch (Exception e) { Thread.Sleep(1000); if (this.audioProcessing == true) { afterFailed(); } return; } Thread.Sleep(processCheckInterval); //checkNum = checkCmdRunning(checkNum, checkF); //if (checkNum == -1) //{ // return; //} } ClearUIAfterAudioProcessing(); process.CancelErrorRead(); process.CancelOutputRead(); this.rsForm.SetTaskStepsLabel(false, 2, 3, VIDEOENCODE); // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1 if (isfailed) { return; } VideoEncode(); // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1 if (isfailed) { return; } Mux(); break; default: cmd = ""; break; } //MessageBox.Show(cmd); }
public void Run() { var command = "/C node \"" + config.OptimizerPath + "\" -o \"" + config.BuildFilePath + "\""; var process = new Process { StartInfo = new ProcessStartInfo { FileName = "cmd.exe", Arguments = command, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true }, EnableRaisingEvents = true }; process.OutputDataReceived += (s, e) => { Console.WriteLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); }
public static int RunProcessAndRedirectToLogger(string command, string parameters, string workingDirectory, LoggerResult logger) { var process = new Process { StartInfo = new ProcessStartInfo(command) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, WorkingDirectory = workingDirectory, Arguments = parameters, } }; process.Start(); DataReceivedEventHandler outputDataReceived = (_, args) => LockProcessAndAddDataToLogger(process, logger, false, args); DataReceivedEventHandler errorDataReceived = (_, args) => LockProcessAndAddDataToLogger(process, logger, true, args); process.OutputDataReceived += outputDataReceived; process.ErrorDataReceived += errorDataReceived; process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); process.CancelOutputRead(); process.CancelErrorRead(); process.OutputDataReceived -= outputDataReceived; process.ErrorDataReceived -= errorDataReceived; return process.ExitCode; }
public static void RunProcess(string name, string args, IList<string> stdout) { var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardInput = true, UseShellExecute = false, FileName = name, Arguments = args }; var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) { stdout.Add(e.Data); Console.WriteLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); }
private static Task GetDbDumpTask(Config config) { return Task.Factory.StartNew(() => { var process = new Process { StartInfo = new ProcessStartInfo(config.MongoDumpPath, config.MongoDumpArgs) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true } }; process.OutputDataReceived += (a, e) => Trace.TraceInformation(e.Data); process.ErrorDataReceived += (a, e) => Trace.TraceEvent(TraceEventType.Error, 0, e.Data); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelErrorRead(); process.CancelOutputRead(); process.Close(); Trace.TraceInformation("Dump completed!"); }); }
public int Run(string srcpath) { Process p; p = new Process(); p.StartInfo.FileName = ILASMpath; p.StartInfo.Arguments = srcpath; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); p.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); p.CancelErrorRead(); p.CancelOutputRead(); return p.ExitCode; }
public CSharpCompilerResult Compile(CSharpCompilerArgs args) { if (args == null) throw new ArgumentNullException("args"); var exitCode = 0; var outputText = string.Empty; var invocationError = null as Exception; var warnings = new List<string>(); var errors = new List<string>(); var framework = new FrameworkVersion40Info(); var compilerArgs = this.GetCompilerArgString(args); var psi = new ProcessStartInfo(framework.CSharpCompilerBinFilepath, compilerArgs); psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.WorkingDirectory = args.WorkDir; psi.CreateNoWindow = true; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = false; var process = new Process(); process.StartInfo = psi; process.ErrorDataReceived += (s, e) => { Console.WriteLine(e.Data); }; process.OutputDataReceived += (s, e) => { Console.WriteLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); process.CancelErrorRead(); process.CancelOutputRead(); exitCode = process.ExitCode; process.Dispose(); process = null; return new CSharpCompilerResult(exitCode, invocationError, outputText, args.OutputFilepath, warnings, errors); }
internal static ProcessOutput StartAndWaitForReady(System.Diagnostics.Process process, int timeoutInSeconds, string processReadyIdentifier, string windowTitle) { if (timeoutInSeconds < 1 || timeoutInSeconds > 10) { throw new ArgumentOutOfRangeException("timeoutInSeconds", "The amount in seconds should have a value between 1 and 10."); } List <string> errorOutput = new List <string>(); List <string> standardOutput = new List <string>(); bool processReady = false; process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data); process.OutputDataReceived += (sender, args) => { standardOutput.Add(args.Data); if ( !string.IsNullOrEmpty(args.Data) && args.Data.Contains(processReadyIdentifier) ) { processReady = true; } }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); int lastResortCounter = 0; int timeOut = timeoutInSeconds * 10; while (!processReady) { System.Threading.Tasks.Task .Delay(100) .Wait(); if (++lastResortCounter > timeOut) { // we waited X seconds. // for any reason the detection did not worked, eg. the identifier changed // lets assume everything is still ok break; } } process.CancelErrorRead(); process.CancelOutputRead(); return(new ProcessOutput(errorOutput, standardOutput, process.ExitCode)); }
private string RunProcesses(List <ProcessStartInfo> processStartInfos, int processTimeoutMs) { var outputBuilder = new StringBuilder(); try { foreach (var processInfo in processStartInfos) { using (var process = new System.Diagnostics.Process()) { //System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = processInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += (sender, eventArgs) => outputBuilder.AppendLine(eventArgs.Data); process.ErrorDataReceived += (sender, eventArgs) => outputBuilder.AppendLine(eventArgs.Data); // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (processTimeoutMs > 0) { var processExited = process.WaitForExit(processTimeoutMs); if (!processExited) { process.Kill(); throw new TimeoutException($"Process did not finish in {processTimeoutMs} ms."); } } else { process.WaitForExit(); } process.CancelOutputRead(); } } return(outputBuilder.ToString()); } catch (InvalidOperationException iEx) { throw; } catch (Exception ex) { throw; } }
public void Run() { if(File.Exists(config.OutputPath)) { options.Log("Deleting old output file.", true); var info = new FileInfo(config.OutputPath); using(info.Create()) { //effectively deletes the contents of the file //calling delete seamed to break the following optimizer code, not sure why } } if(!File.Exists(config.OptimizerPath)) { using(var stream = IO.ReadFromResource("r.js")) using(var file = File.OpenWrite(config.OptimizerPath)) { stream.CopyTo(file); } } if(options.Loader == Options.LoaderOptions.Almond) { if(!File.Exists(config.AlmondPath)) { using(var stream = IO.ReadFromResource("almond-custom.js")) using(var file = File.OpenWrite(config.AlmondPath)) { stream.CopyTo(file); } } } var command = "/C node \"" + config.OptimizerPath + "\" -o \"" + config.BuildFilePath + "\""; var process = new Process { StartInfo = new ProcessStartInfo { FileName = "cmd.exe", Arguments = command, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, }, EnableRaisingEvents = true }; process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (s, e) => Console.Error.WriteLine(e.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); process.CancelOutputRead(); process.CancelErrorRead(); }
public string diskPart(string script) { string output = ""; System.Diagnostics.Process pProcess = new System.Diagnostics.Process(); pProcess.StartInfo.FileName = "DiskPart.exe"; string arguments = "/s \"" + script + "\""; if (variables.debugme) { Console.WriteLine(arguments); } pProcess.StartInfo.Arguments = arguments; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.WorkingDirectory = variables.pathforit; pProcess.StartInfo.RedirectStandardInput = true; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.CreateNoWindow = true; //pProcess.Exited += new EventHandler(xeExit); try { AutoResetEvent outputWaitHandle = new AutoResetEvent(false); pProcess.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { output += e.Data + "\n"; if (!e.Data.Contains("percent")) { Console.WriteLine(e.Data); } } }; pProcess.Start(); pProcess.BeginOutputReadLine(); pProcess.WaitForExit(); if (pProcess.HasExited) { pProcess.CancelOutputRead(); } } catch (Exception objException) { Console.WriteLine(objException.Message); } return(output); }
private void designerOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { if (!String.IsNullOrEmpty(outLine.Data)) { try { designerPort = Convert.ToInt32(outLine.Data); System.Diagnostics.Process tmp = sendingProcess as System.Diagnostics.Process; tmp.CancelOutputRead(); portFound.Set(); } catch { } } }
private static void WaitForExit(Process process) { process.ErrorDataReceived += (sender, args) => Trace.TraceError("NODEJS: {0}".E(args.Data)); process.OutputDataReceived += (sender, args) => Trace.TraceInformation("NODEJS: {0}".I(args.Data)); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelErrorRead(); process.CancelOutputRead(); }
public void Dispose() { if (disposed) { return; } disposed = true; try { if (internalProcess != null) { internalProcess.OutputDataReceived -= InternalProcessOnOutputDataReceived; internalProcess.ErrorDataReceived -= InternalProcessOnErrorDataReceived; internalProcess.Exited -= InternalProcessOnExited; internalProcess.EnableRaisingEvents = false; if (errorReadStarted) { internalProcess.CancelErrorRead(); } if (outputReadStarted) { internalProcess.CancelOutputRead(); } if (killOnDispose && !internalProcess.HasExited) { internalProcess.StandardInput.WriteLine(); KillProcessAndChildren(internalProcess.Id); } internalProcess.Dispose(); } } catch (Exception e) { string additionalInformation = string.Empty; try { if (internalProcess != null) { additionalInformation = $"{internalProcess.MainWindowTitle} - {internalProcess.Id} : {internalProcess.HasExited} - {internalProcess.ExitTime}"; } } catch (Exception) { //do nothing only for information gathering } executionContext.WriteVerbose($"Error while closing process {e}{Environment.NewLine}{additionalInformation}"); } }
public static string Run(string path, string args, out string error, bool readOutputByLines = false) { try { using (Process process = new Process()) { Console.WriteLine("Run: " + path); Console.WriteLine("Args: " + args); process.StartInfo.FileName = path; process.StartInfo.Arguments = args; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; var reterror = ""; var retout = ""; process.OutputDataReceived += (sender, outargs) => { if (retout != "" && outargs.Data != "") retout += "\r\n"; retout += outargs.Data; Console.WriteLine("stdout: {0}", retout); }; process.ErrorDataReceived += (sender, errargs) => { if (reterror != "" && errargs.Data != "") reterror += "\r\n"; reterror += errargs.Data; Console.WriteLine("stderr: {0}", reterror); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); process.CancelOutputRead(); process.CancelErrorRead(); error = reterror; if (process.ExitCode != 0) throw new Exception("Exit Code is not 0"); return readOutputByLines ? string.Empty : retout.Trim().Replace(@"\\", @"\"); } } catch (Exception exception) { error = string.Format("Calling {0} caused an exception: {1}.", path, exception.Message); return string.Empty; } }
private bool WaitProcessExit(System.Diagnostics.Process proc, int milliseconds) { bool success = proc.WaitForExit(milliseconds); if (success) { proc.WaitForExit(); // process stdout and stderr } else { proc.CancelOutputRead(); proc.CancelErrorRead(); } proc.Close(); return(success); }
private static void RunTestProcess(string processPath) { var processStartInfo = new ProcessStartInfo(processPath) { RedirectStandardOutput = true, UseShellExecute = false, }; var process = new Process() { StartInfo = processStartInfo, }; process.OutputDataReceived += Process_OutputDataReceived; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); }
public static void ExecuteCommandSync(object parameters) { ExecuteParameters param = (ExecuteParameters)parameters; try { System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + param.Command); procStartInfo.RedirectStandardOutput = true; procStartInfo.RedirectStandardError = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; procStartInfo.ErrorDialog = false; foreach (EnvVar var in param.Env) { if (var.Name == "path") { procStartInfo.EnvironmentVariables["path"] = procStartInfo.EnvironmentVariables["path"] + var.Value; } else { procStartInfo.EnvironmentVariables.Add(var.Name, var.Value); } Logger.GetInstance().Debug(param.Prefix + " EvnVar:" + var.Name + " = " + procStartInfo.EnvironmentVariables[var.Name]); } System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; Logger.GetInstance().Debug(param.Prefix + " starting process: \"" + param.Command + "\""); proc.OutputDataReceived += (sender, args) => SuppressUnnecessaryDebug(param.Prefix, args.Data); proc.ErrorDataReceived += (sender, args) => SuppressUnnecessaryError(param.Prefix, args.Data); proc.EnableRaisingEvents = true; proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); proc.CancelErrorRead(); proc.CancelOutputRead(); Logger.GetInstance().Debug(param.Prefix + " process exited."); } catch (Exception e) { Logger.GetInstance().Error(param.Prefix + " " + e); } }
static void Main(string[] args) { Console.WriteLine("Please enter your file path to search."); Console.Write("> "); string path = Console.ReadLine(); string[] filenames = Directory.GetFiles(path, "*.mkv", SearchOption.AllDirectories); foreach (string s in filenames) { if (File.Exists(s)) { currentFile = s; Process p = new Process(); p.StartInfo.Arguments = "-i " + "\"" + s + "\""; p.StartInfo.FileName = "ffmpeg.exe"; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.ErrorDataReceived += P_ErrorDataReceived; p.OutputDataReceived += P_ErrorDataReceived; p.WaitForExit(); if (p.HasExited) { p.CancelErrorRead(); p.CancelOutputRead(); p.Close(); } } } convertFiles = convertFiles.Distinct().ToList(); Console.WriteLine("File to convert: " + convertFiles.Count); runThread1(); runThread2(); runThread3(); runThread4(); Console.Write("Press any key to exit."); Console.ReadKey(); }
public void Run() { if(File.Exists(config.OutputPath)) { options.Log("Deleting old output file.", true); File.Delete(config.OutputPath); } if(!File.Exists(config.OptimizerPath)) { using(var stream = IO.ReadFromResource("r.js")) using(var file = File.OpenWrite(config.OptimizerPath)) { stream.CopyTo(file); } } if(options.Almond) { if(!File.Exists(config.AlmondPath)) { using(var stream = IO.ReadFromResource("almond-custom.js")) using(var file = File.OpenWrite(config.AlmondPath)) { stream.CopyTo(file); } } } var command = "/C node \"" + config.OptimizerPath + "\" -o \"" + config.BuildFilePath + "\""; var process = new Process { StartInfo = new ProcessStartInfo { FileName = "cmd.exe", Arguments = command, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true }, EnableRaisingEvents = true }; process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); }
public static string Execute(string program, string arguments) { StringBuilder outputBuilder; ProcessStartInfo processStartInfo; Process process; outputBuilder = new StringBuilder(); processStartInfo = new ProcessStartInfo(); processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardInput = true; processStartInfo.UseShellExecute = false; processStartInfo.Arguments = arguments; processStartInfo.FileName = program; process = new Process(); process.StartInfo = processStartInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { // append the new data to the data already read-in outputBuilder.Append(e.Data); outputBuilder.Append(Environment.NewLine); } ); // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); // use the output string output = outputBuilder.ToString(); return output; }
public bool Spawn(String args, out string result) { StringBuilder outputBuilder; ProcessStartInfo processStartInfo; Process process; outputBuilder = new StringBuilder(); processStartInfo = new ProcessStartInfo(EXE_IN_FULL_PATH, args); processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardInput = true; processStartInfo.UseShellExecute = false; processStartInfo.WindowStyle = ProcessWindowStyle.Normal; using (process = new Process()) { process.StartInfo = processStartInfo; process.EnableRaisingEvents = true; process.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { outputBuilder.Append(e.Data); } ); process.Start(); process.BeginOutputReadLine(); bool terminated = process.WaitForExit(10*1000); process.CancelOutputRead(); if (!terminated) { process.Kill(); result = null; return false; } else { result = outputBuilder.ToString(); return true; } } }
internal static ProcessOutput StartAndWaitForExit(System.Diagnostics.Process process, string windowTitle) { List <string> errorOutput = new List <string>(); List <string> standardOutput = new List <string>(); process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data); process.OutputDataReceived += (sender, args) => standardOutput.Add(args.Data); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelErrorRead(); process.CancelOutputRead(); return(new ProcessOutput(errorOutput, standardOutput, process.ExitCode)); }
public static ProcessOutput StartAndWaitForExit(Process process, string windowTitle) { List<string> errorOutput = new List<string>(); List<string> standardOutput = new List<string>(); process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data); process.OutputDataReceived += (sender, args) => standardOutput.Add(args.Data); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelErrorRead(); process.CancelOutputRead(); return new ProcessOutput(errorOutput, standardOutput); }
public static void ShutdownProcess(Process process) { if (process == null) return; Trace.WriteLine(string.Format(" Trying to close the process {0}", process.ProcessName)); // send Ctrl-C to the process so it can clean up process.StandardInput.WriteLine("q"); process.StandardInput.Close(); process.CancelOutputRead(); process.WaitForExit(30 * 1000); if (!process.HasExited) { Trace.WriteLine(string.Format(" Terminating the process {0} forcibly", process.ProcessName)); KillProcessAndChildren(process.Id); } }
private void NmapExec(object sender, DoWorkEventArgs e) { Process compiler = new Process(); compiler.StartInfo.FileName = NmapLocation; compiler.StartInfo.UseShellExecute = false; compiler.StartInfo.RedirectStandardInput = false; compiler.StartInfo.RedirectStandardOutput = true; compiler.StartInfo.RedirectStandardError = true; compiler.StartInfo.CreateNoWindow = true; compiler.OutputDataReceived += OutputDataHandler; compiler.ErrorDataReceived += OutputDataHandler; compiler.StartInfo.Arguments = (string)e.Argument; compiler.Start(); compiler.BeginOutputReadLine(); compiler.BeginErrorReadLine(); compiler.WaitForExit(); compiler.CancelOutputRead(); compiler.CancelErrorRead(); compiler.Close(); }
/// <summary> /// 启动程序 /// </summary> /// <param name="fileName"></param> /// <param name="args"></param> /// <param name="isGetResults"> </param> private static String CallProcess(string fileName, string args, Boolean isGetResults) { var process = new Process(); process.StartInfo.FileName = fileName;//设置运行的命令行文件 process.StartInfo.Arguments = args;//设置命令参数 process.StartInfo.CreateNoWindow = true;//不显示dos命令行窗口 process.StartInfo.UseShellExecute = false;//是否指定操作系统外壳进程启动程序 process.StartInfo.RedirectStandardOutput = isGetResults; process.StartInfo.RedirectStandardError = isGetResults; // 启动 process.Start(); var result = new StringBuilder(); if (isGetResults) { process.OutputDataReceived += (s, e) => result.AppendLine(e.Data); process.ErrorDataReceived += (s, e) => result.AppendLine(e.Data); process.BeginErrorReadLine(); process.BeginOutputReadLine(); } // 等待完成 process.WaitForExit(); if (isGetResults) { process.CancelOutputRead(); process.CancelErrorRead(); return result.ToString(); } else { return ""; } }
private static void RunGame(string seed) { string expected = string.Format(baseDir + @"expected-{0}.txt", seed); actualFilePath = string.Format(baseDir + @"actual-{0}.txt", seed); File.Delete(actualFilePath); Process x = new Process(); x.StartInfo.FileName = GetExecFolder() + @"\Trivia.exe"; x.StartInfo.Arguments = seed; x.StartInfo.UseShellExecute = false; x.StartInfo.RedirectStandardOutput = true; x.OutputDataReceived += MyProcOutputHandler; x.Start(); x.BeginOutputReadLine(); x.WaitForExit(); x.CancelOutputRead(); Assert.AreEqual(File.ReadAllText(expected), File.ReadAllText(actualFilePath)); }
public static string GetOutputFromProcess(string processName, string arguments) { ProcessStartInfo processStartInfo = new ProcessStartInfo { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardInput = true, UseShellExecute = false, Arguments = arguments, FileName = processName }; StringBuilder outputBuilder = new StringBuilder(); Process process = new Process {StartInfo = processStartInfo, EnableRaisingEvents = true}; process.OutputDataReceived += (sender, e) => outputBuilder.AppendLine(e.Data); process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); // use the output return outputBuilder.ToString(); }
public static bool Build() { FixChartJsBlazorMap(); int exitCode; using (System.Diagnostics.Process pProcess = new System.Diagnostics.Process()) { pProcess.StartInfo.WorkingDirectory = "../sc2dsstats.app"; pProcess.StartInfo.FileName = "electronize"; pProcess.StartInfo.Arguments = "build /target win /package-json ./package.json /electron-params --publish=always /p:PublishSingleFile=false"; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; pProcess.StartInfo.CreateNoWindow = true; pProcess.OutputDataReceived += (sender, args) => { Program.logger?.LogInformation(args.Data); }; pProcess.ErrorDataReceived += (sender, args) => { Program.logger?.LogError(args.Data); }; pProcess.Start(); pProcess.BeginOutputReadLine(); pProcess.BeginErrorReadLine(); // string output = pProcess.StandardOutput.ReadToEnd(); pProcess.WaitForExit(); pProcess.CancelOutputRead(); pProcess.CancelErrorRead(); exitCode = pProcess.ExitCode; } if (exitCode == 0) { Program.logger?.LogInformation($"Electronize finished with ExitCode {exitCode}"); return(true); } else { Program.logger?.LogError($"Electronize failed with ExitCode {exitCode}"); return(false); } }
public void BeginGetDirectoryListing(string path, DirListingCallback callback) { if (m_Session == null) { callback(RequestResult.SessionInvalid, null); return; } List<FileEntry> files = new List<FileEntry>(); Stopwatch timeoutWatch = new Stopwatch(); /* * Check that we have a username either stored from previous sessions, or loaded * from the registry. If PPK Authentication is being used that will override * any values entered in the login dialog */ if (String.IsNullOrEmpty(m_Session.Username)) { if (m_Login.ShowDialog(SuperPuTTY.MainForm) == System.Windows.Forms.DialogResult.OK) { m_Session.Username = m_Login.Username; m_Session.Password = m_Login.Password; if (m_Login.Remember) { //Session.SaveToRegistry(); // passwords are *never* saved and stored permanently SuperPuTTY.SaveSessions(); } } else { Logger.Log("Cancel connection"); callback(RequestResult.CancelLogin, null); } } Thread threadListFiles = new Thread(delegate() { m_processDir = new Process(); m_processDir.EnableRaisingEvents = true; m_processDir.StartInfo.UseShellExecute = false; m_processDir.StartInfo.RedirectStandardError = true; //m_processDir.StartInfo.RedirectStandardInput = true; m_processDir.StartInfo.RedirectStandardOutput = true; m_processDir.StartInfo.CreateNoWindow = true; m_processDir.StartInfo.FileName = SuperPuTTY.Settings.PscpExe; // process the various options from the session object and convert them into arguments pscp can understand string args = MakeArgs(m_Session, true, path); Logger.Log("Sending Command: '{0} {1}'", m_processDir.StartInfo.FileName, MakeArgs(m_Session, false, path)); m_processDir.StartInfo.Arguments = args; /* * Handle output from spawned pscp.exe process, handle any data received and parse * any lines that look like a directory listing. */ m_processDir.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { if (!String.IsNullOrEmpty(e.Data)) { if (e.Data.Equals(PUTTY_ARGUMENTS_HELP_HEADER)) { m_processDir.CancelOutputRead(); m_processDir.Kill(); return; } else if (e.Data.StartsWith("Listing directory ")) { // This just tells us the current directory, however since we're the ones that requested it // we already have this information. But this traps it so its not sent through the directory // entry parser. } else if (e.Data.Equals(PUTTY_INTERACTIVE_AUTH) || e.Data.Contains("password: "******"Username/Password invalid or not sent"); callback(RequestResult.RetryAuthentication, null); } else { timeoutWatch.Reset(); lock (files) { FileEntry file; if (TryParseFileLine(e.Data, out file)) { files.Add(file); } if (files.Count > 0) { callback(RequestResult.ListingFollows, files); } } } } }; m_processDir.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { if (!String.IsNullOrEmpty(e.Data)) { if (e.Data.Contains(PUTTY_NO_KEY)) { m_processDir.CancelErrorRead(); m_processDir.Kill(); System.Windows.Forms.MessageBox.Show("The key of the host you are attempting to connect to has changed or is not cached \n" + "You must connect to this host with with a PuTTY ssh terminal to accept the key and store it in the cache", "Host Key not found or changed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop); } else { Logger.Log("Error Data:\n\t'{0}'", e.Data.TrimEnd()); // 'ssh_init: Host does not exist' } } }; m_processDir.Exited += delegate(object sender, EventArgs e) { if (m_processDir.ExitCode != 0) { Logger.Log("Process Exited (Failure): {0}", m_processDir.ExitCode); callback(RequestResult.UnknownError, null); if (m_PuttyClosed != null) m_PuttyClosed(true); } else { Logger.Log("Process Exited: {0}", m_processDir.ExitCode); if (m_PuttyClosed != null) m_PuttyClosed(false); } m_DirIsBusy = false; }; try { m_processDir.Start(); } catch (Win32Exception e) { if (e.NativeErrorCode == 2) // File Not Found { Logger.Log(e); } else if (e.NativeErrorCode == 4) // Acess Denied { Logger.Log(e); } } m_processDir.BeginErrorReadLine(); m_processDir.BeginOutputReadLine(); m_processDir.WaitForExit(); }); /* Only allow one directory list request at a time */ if (!m_DirIsBusy) { m_DirIsBusy = true; threadListFiles.Name = "List Remote Directory"; threadListFiles.IsBackground = true; threadListFiles.Start(); } else { return; } Thread timeoutThread = new Thread(delegate() { while (m_DirIsBusy) { /* * if no data received in 5 seconds we'll stop the process, * This allows us to capture any interactive prompts/messages * sent to us by putty. */ if (timeoutWatch.Elapsed.Seconds >= 5) { Logger.Log("Timeout after {0} seconds", timeoutWatch.Elapsed.Seconds); if (!m_processDir.HasExited) { m_processDir.Kill(); } m_processDir.CancelErrorRead(); m_processDir.CancelOutputRead(); return; } Thread.Sleep(1000); } }); timeoutThread.Name = "Timeout Watcher"; timeoutThread.IsBackground = true; timeoutThread.Start(); timeoutWatch.Start(); }
private string RunSingleProcess(CommandExecutionParamModel model, int processTimeoutMs) { var process = new System.Diagnostics.Process(); var output = string.Empty; try { var outputBuilder = new StringBuilder(); ProcessStartInfo processStartInfo = new ProcessStartInfo { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardInput = true, RedirectStandardError = true, UseShellExecute = false, ErrorDialog = false, FileName = model.Command }; process.StartInfo = processStartInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += (sender, eventArgs) => outputBuilder.AppendLine(eventArgs.Data); process.ErrorDataReceived += (sender, eventArgs) => outputBuilder.AppendLine(eventArgs.Data); // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (processTimeoutMs > 0) { var processExited = process.WaitForExit(processTimeoutMs); if (!processExited) { process.Kill(); throw new TimeoutException($"Process did not finish in {processTimeoutMs} ms."); } } else { process.WaitForExit(); } process.CancelOutputRead(); output = outputBuilder.ToString(); return(output); } catch (Exception e) { // Console.WriteLine(e.Message); throw; } finally { process.Close(); } }
public override void StartBuild(ProjectBuildOptions options, IBuildFeedbackSink feedbackSink) { string productDir = GetPathFromRegistry(@"SOFTWARE\Microsoft\VisualStudio\9.0\Setup\VC", "ProductDir"); string batFile = "vcvars32.bat"; if (options.Platform == "x64") { batFile = "vcvars64.bat"; } string commonTools = GetFile(productDir != null ? Path.Combine(productDir, "bin\\" + batFile) : null) ?? GetFile("%VS90COMNTOOLS%\\" + batFile) ?? GetFile("%VS80COMNTOOLS%\\" + batFile); Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/C"; if (!string.IsNullOrEmpty(commonTools)) { p.StartInfo.Arguments += " call \"" + commonTools + "\" &&"; } p.StartInfo.Arguments += " vcbuild"; if (options.Target == BuildTarget.Build) { // OK } else if (options.Target == BuildTarget.Clean) { p.StartInfo.Arguments += " /clean"; } else if (options.Target == BuildTarget.Rebuild) { p.StartInfo.Arguments += " /rebuild"; } p.StartInfo.Arguments += " /showenv"; p.StartInfo.Arguments += " \"" + this.FileName + "\""; p.StartInfo.Arguments += " \"/error:Error: \""; p.StartInfo.Arguments += " \"/warning:Warning: \""; p.StartInfo.WorkingDirectory = this.Directory; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.EnvironmentVariables["VCBUILD_DEFAULT_CFG"] = options.Configuration + "|" + options.Platform; p.StartInfo.EnvironmentVariables["SolutionPath"] = ParentSolution.FileName; p.EnableRaisingEvents = true; p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { BuildError error = ParseError(e.Data); if (error != null) feedbackSink.ReportError(error); else feedbackSink.ReportMessage(e.Data); } }; p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { BuildError error = ParseError(e.Data); if (error != null) feedbackSink.ReportError(error); else feedbackSink.ReportError(new BuildError(null, e.Data)); } }; p.Exited += delegate(object sender, EventArgs e) { p.CancelErrorRead(); p.CancelOutputRead(); feedbackSink.Done(p.ExitCode == 0); p.Dispose(); }; feedbackSink.ReportMessage("Building " + this.Name); feedbackSink.ReportMessage(p.StartInfo.FileName + " " + p.StartInfo.Arguments); p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); }
private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames) { if (null == options) throw new ArgumentNullException("options"); if (null == fileNames) throw new ArgumentNullException("fileNames"); CompilerResults results = new CompilerResults(options.TempFiles); Process mcs = new Process(); #if !NET_2_0 string mcs_output; string mcs_stdout; string[] mcsOutput; #endif // FIXME: these lines had better be platform independent. if (Path.DirectorySeparatorChar == '\\') { mcs.StartInfo.FileName = windowsMonoPath; mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " + #if NET_2_0 BuildArgs (options, fileNames, ProviderOptions); #else BuildArgs(options, fileNames); #endif } else { #if NET_2_0 // FIXME: This is a temporary hack to make code genaration work in 2.0+ #if NET_4_0 mcs.StartInfo.FileName="dmcs"; #else mcs.StartInfo.FileName="gmcs"; #endif mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions); #else mcs.StartInfo.FileName = "mcs"; mcs.StartInfo.Arguments = BuildArgs(options, fileNames); #endif } #if NET_2_0 mcsOutput = new StringCollection (); mcsOutMutex = new Mutex (); #endif string monoPath = Environment.GetEnvironmentVariable("MONO_PATH"); if (monoPath == null) monoPath = String.Empty; string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (privateBinPath != null && privateBinPath.Length > 0) monoPath = String.Format("{0}:{1}", privateBinPath, monoPath); if (monoPath.Length > 0) { StringDictionary dict = mcs.StartInfo.EnvironmentVariables; if (dict.ContainsKey("MONO_PATH")) dict["MONO_PATH"] = monoPath; else dict.Add("MONO_PATH", monoPath); } mcs.StartInfo.CreateNoWindow = true; mcs.StartInfo.UseShellExecute = false; mcs.StartInfo.RedirectStandardOutput = true; mcs.StartInfo.RedirectStandardError = true; #if NET_2_0 mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived); #endif try { mcs.Start(); } catch (Exception e) { Win32Exception exc = e as Win32Exception; if (exc != null) { /*throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName, Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));*/ } throw; } try { #if NET_2_0 mcs.BeginOutputReadLine (); mcs.BeginErrorReadLine (); #else // If there are a few kB in stdout, we might lock mcs_output = mcs.StandardError.ReadToEnd(); mcs_stdout = mcs.StandardOutput.ReadToEnd(); #endif mcs.WaitForExit(); results.NativeCompilerReturnValue = mcs.ExitCode; } finally { #if NET_2_0 mcs.CancelErrorRead (); mcs.CancelOutputRead (); #endif mcs.Close(); } #if NET_2_0 StringCollection sc = mcsOutput; #else mcsOutput = mcs_output.Split(System.Environment.NewLine.ToCharArray()); StringCollection sc = new StringCollection(); #endif bool loadIt = true; foreach (string error_line in mcsOutput) { #if !NET_2_0 sc.Add(error_line); #endif CompilerError error = CreateErrorFromString(error_line); if (error != null) { results.Errors.Add(error); if (!error.IsWarning) loadIt = false; } } if (sc.Count > 0) { sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine); //results.Output = sc; } if (loadIt) { if (!File.Exists(options.OutputAssembly)) { StringBuilder sb = new StringBuilder(); foreach (string s in sc) sb.Append(s + Environment.NewLine); throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'"); } if (options.GenerateInMemory) { using (FileStream fs = File.OpenRead(options.OutputAssembly)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence); fs.Close(); } } else { // Avoid setting CompiledAssembly right now since the output might be a netmodule results.PathToAssembly = options.OutputAssembly; } } else { results.CompiledAssembly = null; } return results; }
public static string nmapOsScan(string serverName) { StringBuilder output; ProcessStartInfo processStartInfo; Process process; output = new StringBuilder(); processStartInfo = new ProcessStartInfo(); processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardInput = true; processStartInfo.UseShellExecute = false; processStartInfo.Arguments = " -O --osscan-limit --osscan-guess --max-os-tries 1 " + serverName; processStartInfo.FileName = "nmap.exe"; process = new Process(); process.StartInfo = processStartInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; process.OutputDataReceived += (sender, args) => output.Append(args.Data + '\n'); process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); // use the output string result = output.ToString(); string guesses = result.Split('\n').Where(x => x.StartsWith("Aggressive OS guesses: ")).FirstOrDefault().Replace("Aggressive OS guesses: ", ""); return guesses; }
public AppFinder() { if (Application.platform == RuntimePlatform.OSXPlayer) { ValkyrieDebug.Log("Attempting to locate AppId " + AppId() + " on MacOS."); System.Diagnostics.ProcessStartInfo processStartInfo; System.Diagnostics.Process process; StringBuilder outputBuilder = new StringBuilder(); processStartInfo = new System.Diagnostics.ProcessStartInfo(); processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardInput = true; processStartInfo.UseShellExecute = false; processStartInfo.Arguments = "SPApplicationsDataType -xml"; processStartInfo.FileName = "system_profiler"; process = new System.Diagnostics.Process(); ValkyrieDebug.Log("Starting system_profiler."); process.StartInfo = processStartInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler ( delegate(object sender, System.Diagnostics.DataReceivedEventArgs e) { // append the new data to the data already read-in outputBuilder.Append(e.Data); } ); // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); string[] output = outputBuilder.ToString().Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); ValkyrieDebug.Log("Number of lines returned: " + output.Length); if (output.Length == 1) { ValkyrieDebug.Log(output[0]); } ValkyrieDebug.Log("Looking for: " + "/" + Executable()); // Quick hack rather than doing XML properly foreach (string s in output) { if (s.IndexOf("/" + Executable()) > 0) { ValkyrieDebug.Log("Found Line: " + s); location = s.Trim(); // Removing <string> and </string> location = location.Substring(8, location.Length - 17); ValkyrieDebug.Log("Using location: " + location); } } if (location.Length == 0) { location = "~/Library/Application Support/Steam/steamapps/common/Mansions of Madness/Mansions of Madness.app"; ValkyrieDebug.Log("Could not find, using magic locatoin: " + location); } } else { // Attempt to get steam install location (current 32/64 level) location = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation", ""); if (location.Equals("")) { // If we are on a 64 bit system, need to read the 64bit registry from a 32 bit app (Valkyrie) try { location = RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation"); } catch (Exception) { } } } exeLocation += location + "/" + Executable(); location += DataDirectory(); ValkyrieDebug.Log("Asset location: " + location); }
/// <summary> /// Start the process in an async manner /// </summary> /// <param name="startInfo"> /// The <see cref="ProcessStartInfo" /> describing the process to launch /// </param> /// <param name="outputMessage"> /// Callback for each line of text emitted on the launched Process's Standard Output Stream /// </param> /// <param name="errorMessage"> /// Callback for each line of text emitted on the launched Process's Standard Error Stream /// </param> /// <param name="startedCallback"> /// Callback invoked with the started <see cref="Process" /> /// </param> /// <param name="cancellationToken"> /// The cancellation token. /// </param> /// <returns> /// The <see cref="Task" /> representing the executing process. The completed result will be the exit code value. /// </returns> /// <exception cref="InvalidOperationException"> /// Thrown if the process cannot be started /// </exception> public static async Task <int> StartAsync( [NotNull] this ProcessStartInfo startInfo, Action <string> outputMessage, Action <string> errorMessage, Action <Process> startedCallback, CancellationToken cancellationToken) { startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; var tcs = new TaskCompletionSource <int>(); var ps = new Process { StartInfo = startInfo, EnableRaisingEvents = true }; ps.Exited += (sender, eventArgs) => { ps.WaitForExit(); var code = ps.ExitCode; ps.CancelErrorRead(); ps.CancelOutputRead(); ps.Dispose(); tcs.TrySetResult(code); }; using (cancellationToken.Register( () => { tcs.TrySetCanceled(); try { if (ps.HasExited) { return; } ps.Kill(); ps.WaitForExit(WaitForExitDelayInMilliseconds); ps.WaitForExit(); ps.Dispose(); } catch (InvalidOperationException) { // Ignore } })) { cancellationToken.ThrowIfCancellationRequested(); ps.OutputDataReceived += (s, e) => { if (e.Data != null) { PushLine(e.Data, outputMessage); } }; ps.ErrorDataReceived += (s, e) => { if (e.Data != null) { PushLine(e.Data, errorMessage ?? outputMessage); } }; ps.Start(); ps.BeginErrorReadLine(); ps.BeginOutputReadLine(); startedCallback?.Invoke(ps); return(await tcs.Task.ConfigureAwait(false)); } }
/// <summary> /// Reads from Output stream to determine if process is ready /// </summary> public static ProcessOutput StartAndWaitForReady(Process process, int timeoutInSeconds, string processReadyIdentifier, string windowTitle) { if (timeoutInSeconds < 1 || timeoutInSeconds > 10) { throw new ArgumentOutOfRangeException("timeoutInSeconds", "The amount in seconds should have a value between 1 and 10."); } List<string> errorOutput = new List<string>(); List<string> standardOutput = new List<string>(); bool processReady = false; process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data); process.OutputDataReceived += (sender, args) => { standardOutput.Add(args.Data); if (!string.IsNullOrEmpty(args.Data) && args.Data.Contains(processReadyIdentifier)) { processReady = true; } }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); int lastResortCounter = 0; int timeOut = timeoutInSeconds * 10; while (!processReady) { Thread.Sleep(100); if (++lastResortCounter > timeOut) { // we waited X seconds. // for any reason the detection did not worked, eg. the identifier changed // lets assume everything is still ok break; } } process.CancelErrorRead(); process.CancelOutputRead(); return new ProcessOutput(errorOutput, standardOutput); }
public MainWindow() { InitializeComponent(); _infoProcess = new Process() { EnableRaisingEvents = true }; _probeProcess = new Process() { EnableRaisingEvents = true }; _dumpingProcess = new Process() { EnableRaisingEvents = true }; _infoProcess.OutputDataReceived += (sender, args) => { if (args.Data != "" || args.Data != null) { _songInfo = JsonConvert.DeserializeObject <MDOut>(args.Data); _infoProcess.CancelOutputRead(); this.Dispatcher.Invoke(() => { txtGame.Text = _songInfo.Containerinfo.Game; txtSystem.Text = _songInfo.Containerinfo.System; txtDumper.Text = _songInfo.Containerinfo.Dumper; txtCopyright.Text = _songInfo.Containerinfo.Copyright; thrInfo.Visibility = Visibility.Hidden; thrProbe.Visibility = Visibility.Visible; _channelInfoParsed = new ObservableCollection <ChannelInfo>(); Probe(); var indexed = new List <IndexedSong>(); for (int i = 0; i < _songInfo.Songs.Count; i++) { var s = _songInfo.Songs[i]; s.Name = s.Name == "" ? null : s.Name; indexed.Add(new IndexedSong(i, s)); } lstSubSongs.ItemsSource = indexed; }); } }; _infoProcess.Exited += (sender, args) => { }; double mxp = 0.0; _probeProcess.OutputDataReceived += (sender, args) => { string line = args.Data; if (line == null) { _probeProcess.CancelOutputRead(); return; } if (line != "") { if (line[0] == 'p') { var x = line.Split('|'); mxp = Double.Parse(x[2]); this.Dispatcher.Invoke(() => { thrProbe.Maximum = Double.Parse(x[2]); thrProbe.Value = Double.Parse(x[1]); }); } else { _channelInfo = JsonConvert.DeserializeObject <IncomingChannelInfo>(line); foreach (var channel in _channelInfo.Channels) { _channelInfoParsed.Add(new ChannelInfo() { ChannelName = channel, CurrentProgress = 0.0, MaximumProgress = mxp }); } this.Dispatcher.Invoke(() => { lstInfo.Visibility = Visibility.Visible; lstInfo.ItemsSource = _channelInfoParsed; }); } } }; _probeProcess.Exited += (sender, args) => { this.Dispatcher.Invoke(() => { thrProbe.Visibility = Visibility.Hidden; if (lstSubSongs.SelectedItems.Count != 0) { btnDump.IsEnabled = true; } }); }; string lineD; _dumpingProcess.OutputDataReceived += (sender, args) => { lineD = args.Data; if (lineD == null) { _dumpingProcess.CancelOutputRead(); return; } if (lineD != "") { var x = lineD.Split('|'); _channelInfoParsed[Int32.Parse(x[0])].MaximumProgress = Double.Parse(x[2]); _channelInfoParsed[Int32.Parse(x[0])].CurrentProgress = Double.Parse(x[1]); } }; _dumpingProcess.Exited += (sender, args) => { this.Dispatcher.Invoke(() => { btnLoad.IsEnabled = true; btnDump.IsEnabled = true; }); Process.Start("explorer", $"/select,\"{_ofDialog.FileName}\""); }; }
public void Start(bool redirectStandardOutput = false) { try { string sLog = string.Format("Attempting to start process with command: {0} {1}", ProcessFullPath, string.Join(" ", Arguments)); Log.Instance.OutputLog(sLog, Log.LogLevel.Information); ProcessStartInfo startInf = new ProcessStartInfo(ProcessFullPath); startInf.UseShellExecute = true; startInf.CreateNoWindow = true; startInf.WindowStyle = ProcessWindowStyle; if (redirectStandardOutput) { startInf.RedirectStandardOutput = true; startInf.RedirectStandardInput = true; startInf.UseShellExecute = false; } if (Arguments.Any()) { foreach (var arg in Arguments) { startInf.Arguments += arg.Contains(" ") ? " \"" + arg + "\"" : " " + arg; } } System.Diagnostics.Process proc = new System.Diagnostics.Process { StartInfo = startInf }; proc.StartInfo.Verb = "runas"; if (redirectStandardOutput) { // enable raising events because Process does not raise events by default proc.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process proc.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { // append the new data to the data already read-in Log.Instance.OutputLog(e.Data, Log.LogLevel.Information); } ); } if (!proc.Start()) { sLog = string.Format("Failed to start process: '{0}'", ProcessFullPath); Log.Instance.OutputLog(sLog, Log.LogLevel.Error); } if (redirectStandardOutput) { proc.BeginOutputReadLine(); proc.WaitForExit(); proc.CancelOutputRead(); } } catch (Exception ex) { Log.Instance.OutputLog(ex.Message, Log.LogLevel.Error); } }
void BuildSatelliteAssembly (string cultureName, List <string> files) { string assemblyPath = BuildAssemblyPath (cultureName); var info = new ProcessStartInfo (); var al = new Process (); string arguments = SetAlPath (info); var sb = new StringBuilder (arguments); sb.Append ("/c:\"" + cultureName + "\" "); sb.Append ("/t:lib "); sb.Append ("/out:\"" + assemblyPath + "\" "); if (mainAssembly != null) sb.Append ("/template:\"" + mainAssembly.Location + "\" "); string responseFilePath = assemblyPath + ".response"; using (FileStream fs = File.OpenWrite (responseFilePath)) { using (StreamWriter sw = new StreamWriter (fs)) { foreach (string f in files) sw.WriteLine ("/embed:\"" + f + "\" "); } } sb.Append ("@\"" + responseFilePath + "\""); info.Arguments = sb.ToString (); info.CreateNoWindow = true; info.UseShellExecute = false; info.RedirectStandardOutput = true; info.RedirectStandardError = true; al.StartInfo = info; var alOutput = new StringCollection (); var alMutex = new Mutex (); DataReceivedEventHandler outputHandler = (object sender, DataReceivedEventArgs args) => { if (args.Data != null) { alMutex.WaitOne (); alOutput.Add (args.Data); alMutex.ReleaseMutex (); } }; al.ErrorDataReceived += outputHandler; al.OutputDataReceived += outputHandler; // TODO: consider using asynchronous processes try { al.Start (); } catch (Exception ex) { throw new HttpException (String.Format ("Error running {0}", al.StartInfo.FileName), ex); } Exception alException = null; int exitCode = 0; try { al.BeginOutputReadLine (); al.BeginErrorReadLine (); al.WaitForExit (); exitCode = al.ExitCode; } catch (Exception ex) { alException = ex; } finally { al.CancelErrorRead (); al.CancelOutputRead (); al.Close (); } if (exitCode != 0 || alException != null) { // TODO: consider adding a new type of compilation exception, // tailored for al CompilerErrorCollection errors = null; if (alOutput.Count != 0) { foreach (string line in alOutput) { if (!line.StartsWith ("ALINK: error ", StringComparison.Ordinal)) continue; if (errors == null) errors = new CompilerErrorCollection (); int colon = line.IndexOf (':', 13); string errorNumber = colon != -1 ? line.Substring (13, colon - 13) : "Unknown"; string errorText = colon != -1 ? line.Substring (colon + 1) : line.Substring (13); errors.Add (new CompilerError (Path.GetFileName (assemblyPath), 0, 0, errorNumber, errorText)); } } throw new CompilationException (Path.GetFileName (assemblyPath), errors, null); } }
private static List<GitCommitInfo> ParseGitCommitsSinceLastPackage(ConfigFile config, string gitPath) { List<GitCommitInfo> commitsSinceLastPackage = new List<GitCommitInfo>(); string solutionDir = Path.GetDirectoryName(config.SolutionPath); // Retrieve the git history for the repository ProcessStartInfo gitStartInfo = new ProcessStartInfo { FileName = gitPath, WorkingDirectory = solutionDir, Arguments = "--no-pager log --name-only --oneline --since=\"2015\"", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; Process gitProc = new Process(); gitProc.StartInfo = gitStartInfo; gitProc.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) { if (string.IsNullOrEmpty(e.Data)) return; // Begin of a new commit if (e.Data.Contains(' ')) { string line = e.Data.Trim(); int indexOfSeparator = line.IndexOf(' '); string commitId = line.Substring(0, indexOfSeparator); if (Regex.IsMatch(commitId, @"\b[0-9a-f]{5,40}\b")) { string commitTitleAndMessage = line.Substring(indexOfSeparator, line.Length - indexOfSeparator).Trim(); string[] commitMessageToken = commitTitleAndMessage.Split('#'); string commitTitle; string commitMessage; // Received the expected commit message format in the form // // Title / Headline // #CHANGE: Description // #ADD: More Description // ... if (commitMessageToken.Length > 1) { commitTitle = commitMessageToken[0].Trim(); commitMessage = "#" + string.Join(Environment.NewLine + "#", commitMessageToken, 1, commitMessageToken.Length - 1); } // Received an unexpected message format else { commitMessageToken = commitTitleAndMessage.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); commitTitle = commitMessageToken[0]; commitMessage = string.Empty; } // Stop reading as soon as we see a package update commit if (string.Equals(commitTitle, PackageUpdateCommitTitle, StringComparison.InvariantCultureIgnoreCase) && commitMessage.IndexOf(PackageUpdateCommitMessageBegin, StringComparison.InvariantCultureIgnoreCase) >= 0) { gitProc.CancelOutputRead(); if (!gitProc.HasExited) gitProc.Kill(); return; } // Start collecting files for the new commit commitsSinceLastPackage.Add(new GitCommitInfo { Id = commitId, Title = commitTitle, Message = commitMessage }); return; } } // File list entry GitCommitInfo commitInfo = commitsSinceLastPackage[commitsSinceLastPackage.Count - 1]; string filePathFull = Path.GetFullPath(Path.Combine(solutionDir, e.Data)); commitInfo.FilePaths.Add(filePathFull); return; }; gitProc.Start(); gitProc.BeginOutputReadLine(); gitProc.WaitForExit(); return commitsSinceLastPackage; }
public AppFinder() { if (Application.platform == RuntimePlatform.OSXPlayer) { ValkyrieDebug.Log("Attempting to locate AppId " + AppId() + " on MacOS."); System.Diagnostics.ProcessStartInfo processStartInfo; System.Diagnostics.Process process; StringBuilder outputBuilder = new StringBuilder(); processStartInfo = new System.Diagnostics.ProcessStartInfo(); processStartInfo.CreateNoWindow = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardInput = true; processStartInfo.UseShellExecute = false; processStartInfo.Arguments = "SPApplicationsDataType -xml"; processStartInfo.FileName = "system_profiler"; process = new System.Diagnostics.Process(); ValkyrieDebug.Log("Starting system_profiler."); process.StartInfo = processStartInfo; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler ( delegate(object sender, System.Diagnostics.DataReceivedEventArgs e) { // append the new data to the data already read-in outputBuilder.Append(e.Data); } ); // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); string output = outputBuilder.ToString(); ValkyrieDebug.Log("Looking for: " + "/" + Executable()); // Quick hack rather than doing XML properly int foundAt = output.IndexOf("/" + Executable()); if (foundAt > 0) { ValkyrieDebug.Log("Name Index: " + foundAt); int startPos = output.LastIndexOf("<string>", foundAt) + 8; ValkyrieDebug.Log("Start Index: " + startPos); location = output.Substring(startPos, output.IndexOf("</string>", startPos) - startPos).Trim(); ValkyrieDebug.Log("Using location: " + location); } } else { // Attempt to get steam install location (current 32/64 level) location = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation", ""); if (location.Equals("")) { // If we are on a 64 bit system, need to read the 64bit registry from a 32 bit app (Valkyrie) try { location = RegistryWOW6432.GetRegKey64(RegHive.HKEY_LOCAL_MACHINE, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Steam App " + AppId(), "InstallLocation"); } catch (Exception) { } } } exeLocation += location + "/" + Executable(); location += DataDirectory(); ValkyrieDebug.Log("Asset location: " + location); }
protected virtual bool ExecuteDisassemblerProcess( ProcessStartInfo disassemblerProcessStartInfo, out string disassembledCode) { disassembledCode = null; using (var outputWaitHandle = new AutoResetEvent(false)) { using (var process = new Process()) { process.StartInfo = disassemblerProcessStartInfo; var outputBuilder = new StringBuilder(); process.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { outputBuilder.AppendLine(e.Data); } }; var started = process.Start(); if (started) { process.BeginOutputReadLine(); var exited = process.WaitForExit(GlobalConstants.DefaultProcessExitTimeOutMilliseconds); if (exited) { outputWaitHandle.WaitOne(100); if (process.ExitCode == ProcessSuccessExitCode) { disassembledCode = outputBuilder.ToString().Trim(); return true; } } else { process.CancelOutputRead(); // Double check if the process has exited before killing it if (!process.HasExited) { process.Kill(); } } } return false; } } }
private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames) { if (null == options) throw new ArgumentNullException("options"); if (null == fileNames) throw new ArgumentNullException("fileNames"); CompilerResults results=new CompilerResults(options.TempFiles); Process mcs=new Process(); // FIXME: these lines had better be platform independent. if (Path.DirectorySeparatorChar == '\\') { mcs.StartInfo.FileName = windowsMonoPath; mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " + BuildArgs (options, fileNames, ProviderOptions); } else { mcs.StartInfo.FileName="mcs"; mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions); } mcsOutput = new StringCollection (); mcsOutMutex = new Mutex (); #if !NET_4_0 /* * !:. KLUDGE WARNING .:! * * When running the 2.0 test suite some assemblies will invoke mcs via * CodeDOM and the new mcs process will find the MONO_PATH variable in its * environment pointing to the net_2_0 library which will cause the runtime * to attempt to load the 2.0 corlib into 4.0 process and thus mcs will * fail. At the same time, we must not touch MONO_PATH when running outside * the test suite, thus the kludge. * * !:. KLUDGE WARNING .:! */ if (Environment.GetEnvironmentVariable ("MONO_TESTS_IN_PROGRESS") != null) { string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH"); if (!String.IsNullOrEmpty (monoPath)) { const string basePath = "/class/lib/"; const string profile = "net_2_0"; var basePathIndex = monoPath.IndexOf (basePath, StringComparison.Ordinal); if (basePathIndex > 0 && basePathIndex + basePath.Length + profile.Length <= monoPath.Length) { var currentProfile = monoPath.Substring (basePathIndex + basePath.Length, profile.Length); if (currentProfile.Equals (profile, StringComparison.OrdinalIgnoreCase)) monoPath = monoPath.Replace (basePath + currentProfile, basePath + "net_4_0"); } mcs.StartInfo.EnvironmentVariables ["MONO_PATH"] = monoPath; } } #endif /* string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH"); if (monoPath != null) monoPath = String.Empty; string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (privateBinPath != null && privateBinPath.Length > 0) monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath); if (monoPath.Length > 0) { StringDictionary dict = mcs.StartInfo.EnvironmentVariables; if (dict.ContainsKey ("MONO_PATH")) dict ["MONO_PATH"] = monoPath; else dict.Add ("MONO_PATH", monoPath); } */ /* * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that * may not handle some of the options causing compilation failure */ mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty; mcs.StartInfo.CreateNoWindow=true; mcs.StartInfo.UseShellExecute=false; mcs.StartInfo.RedirectStandardOutput=true; mcs.StartInfo.RedirectStandardError=true; mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived); try { mcs.Start(); } catch (Exception e) { Win32Exception exc = e as Win32Exception; if (exc != null) { throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName, Win32Exception.W32ErrorMessage (exc.NativeErrorCode))); } throw; } try { mcs.BeginOutputReadLine (); mcs.BeginErrorReadLine (); mcs.WaitForExit(); results.NativeCompilerReturnValue = mcs.ExitCode; } finally { mcs.CancelErrorRead (); mcs.CancelOutputRead (); mcs.Close(); } StringCollection sc = mcsOutput; bool loadIt=true; foreach (string error_line in mcsOutput) { CompilerError error = CreateErrorFromString (error_line); if (error != null) { results.Errors.Add (error); if (!error.IsWarning) loadIt = false; } } if (sc.Count > 0) { sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine); results.Output = sc; } if (loadIt) { if (!File.Exists (options.OutputAssembly)) { StringBuilder sb = new StringBuilder (); foreach (string s in sc) sb.Append (s + Environment.NewLine); throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'"); } if (options.GenerateInMemory) { using (FileStream fs = File.OpenRead(options.OutputAssembly)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); results.CompiledAssembly = Assembly.Load(buffer, null); fs.Close(); } } else { // Avoid setting CompiledAssembly right now since the output might be a netmodule results.PathToAssembly = options.OutputAssembly; } } else { results.CompiledAssembly = null; } return results; }
private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames) { if (null == options) throw new ArgumentNullException("options"); if (null == fileNames) throw new ArgumentNullException("fileNames"); CompilerResults results=new CompilerResults(options.TempFiles); Process mcs=new Process(); // FIXME: these lines had better be platform independent. if (Path.DirectorySeparatorChar == '\\') { mcs.StartInfo.FileName = MonoToolsLocator.Mono; mcs.StartInfo.Arguments = "\"" + MonoToolsLocator.CSharpCompiler + "\" "; } else { mcs.StartInfo.FileName = MonoToolsLocator.CSharpCompiler; } mcs.StartInfo.Arguments += BuildArgs (options, fileNames, ProviderOptions); mcsOutput = new StringCollection (); mcsOutMutex = new Mutex (); /* string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH"); if (monoPath != null) monoPath = String.Empty; string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (privateBinPath != null && privateBinPath.Length > 0) monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath); if (monoPath.Length > 0) { StringDictionary dict = mcs.StartInfo.EnvironmentVariables; if (dict.ContainsKey ("MONO_PATH")) dict ["MONO_PATH"] = monoPath; else dict.Add ("MONO_PATH", monoPath); } */ /* * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that * may not handle some of the options causing compilation failure */ mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty; mcs.StartInfo.CreateNoWindow=true; mcs.StartInfo.UseShellExecute=false; mcs.StartInfo.RedirectStandardOutput=true; mcs.StartInfo.RedirectStandardError=true; mcs.OutputDataReceived += new DataReceivedEventHandler (McsStderrDataReceived); // Use same text decoder as mcs and not user set values in Console mcs.StartInfo.StandardOutputEncoding = mcs.StartInfo.StandardErrorEncoding = Encoding.UTF8; try { mcs.Start(); } catch (Exception e) { Win32Exception exc = e as Win32Exception; if (exc != null) { throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName, Win32Exception.GetErrorMessage (exc.NativeErrorCode))); } throw; } try { mcs.BeginOutputReadLine (); mcs.BeginErrorReadLine (); mcs.WaitForExit(); results.NativeCompilerReturnValue = mcs.ExitCode; } finally { mcs.CancelErrorRead (); mcs.CancelOutputRead (); mcs.Close(); } StringCollection sc = mcsOutput; bool loadIt=true; foreach (string error_line in mcsOutput) { CompilerError error = CreateErrorFromString (error_line); if (error != null) { results.Errors.Add (error); if (!error.IsWarning) loadIt = false; } } if (sc.Count > 0) { sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine); results.Output = sc; } if (loadIt) { if (!File.Exists (options.OutputAssembly)) { StringBuilder sb = new StringBuilder (); foreach (string s in sc) sb.Append (s + Environment.NewLine); throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'"); } if (options.GenerateInMemory) { using (FileStream fs = File.OpenRead(options.OutputAssembly)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); results.CompiledAssembly = Assembly.Load(buffer, null); fs.Close(); } } else { // Avoid setting CompiledAssembly right now since the output might be a netmodule results.PathToAssembly = options.OutputAssembly; } } else { results.CompiledAssembly = null; } return results; }
void BuildImageTrackingAssets() { if (Directory.Exists(Application.streamingAssetsPath)) { s_ShouldDeleteStreamingAssetsFolder = false; } else { // Delete the streaming assets folder at the end of the build pipeline // since it did not exist before we created it here. s_ShouldDeleteStreamingAssetsFolder = true; Directory.CreateDirectory(Application.streamingAssetsPath); } if (!Directory.Exists(ARCoreImageTrackingProvider.k_StreamingAssetsPath)) { Directory.CreateDirectory(ARCoreImageTrackingProvider.k_StreamingAssetsPath); } try { string[] libGuids = AssetDatabase.FindAssets("t:xrReferenceImageLibrary"); if (libGuids == null || libGuids.Length == 0) { return; } // This is how much each library will contribute to the overall progress var progressPerLibrary = 1f / libGuids.Length; const string progressBarText = "Building ARCore Image Library"; for (int libraryIndex = 0; libraryIndex < libGuids.Length; ++libraryIndex) { var libGuid = libGuids[libraryIndex]; var overallProgress = progressPerLibrary * libraryIndex; var numSteps = libGuids.Length + 1; // 1 per image plus arcoreimg var libraryPath = AssetDatabase.GUIDToAssetPath(libGuid); var imageLib = AssetDatabase.LoadAssetAtPath <XRReferenceImageLibrary>(libraryPath); EditorUtility.DisplayProgressBar(progressBarText, imageLib.name, overallProgress); var tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); var inputImageListPath = Path.Combine(tempDirectory, Guid.NewGuid().ToString("N") + ".txt"); // prepare text file for arcoreimg to read from try { Directory.CreateDirectory(tempDirectory); using (var writer = new StreamWriter(inputImageListPath, false)) { for (int i = 0; i < imageLib.count; i++) { var referenceImage = imageLib[i]; var textureGuid = referenceImage.textureGuid.ToString("N"); var assetPath = AssetDatabase.GUIDToAssetPath(textureGuid); var referenceImageName = referenceImage.guid.ToString("N"); EditorUtility.DisplayProgressBar( progressBarText, imageLib.name + ": " + assetPath, overallProgress + progressPerLibrary * i / numSteps); var texture = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath); if (texture == null) { throw new BuildFailedException(string.Format( "ARCore Image Library Generation: Reference library at '{0}' is missing a texture at index {1}.", libraryPath, i)); } var extension = Path.GetExtension(assetPath); var entry = new StringBuilder(); if (string.Equals(extension, ".jpg", StringComparison.Ordinal) || string.Equals(extension, ".jpeg", StringComparison.Ordinal) || string.Equals(extension, ".png", StringComparison.Ordinal)) { // If lowercase jpg or png, use image as is entry.Append($"{referenceImageName}|{assetPath}"); } else if (string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase)) { // If jpg or png but NOT lowercase, then copy it to a temporary file that uses lowercase var pathWithLowercaseExtension = Path.Combine(tempDirectory, textureGuid + extension.ToLower()); File.Copy(assetPath, pathWithLowercaseExtension); entry.Append($"{referenceImageName}|{pathWithLowercaseExtension}"); } else { var pngFilename = Path.Combine(tempDirectory, textureGuid + ".png"); var bytes = ImageConversion.EncodeToPNG(texture); if (bytes == null) { throw new BuildFailedException(string.Format( "ARCore Image Library Generation: Texture format for image '{0}' not supported. Inspect other error messages emitted during this build for more details.", texture.name)); } File.WriteAllBytes(pngFilename, bytes); entry.Append($"{referenceImageName}|{pngFilename}"); } if (referenceImage.specifySize) { entry.Append($"|{referenceImage.width.ToString("G", CultureInfo.InvariantCulture)}"); } writer.WriteLine(entry.ToString()); } } } catch { Directory.Delete(tempDirectory, true); throw; } // launch arcoreimg and wait for it to return so we can process the asset try { EditorUtility.DisplayProgressBar( progressBarText, imageLib.name + ": Invoking arcoreimg", overallProgress + progressPerLibrary * (numSteps - 1) / numSteps); var packagePath = Path.GetFullPath("Packages/com.unity.xr.arcore"); string extension = ""; string platformName = "Undefined"; #if UNITY_EDITOR_WIN platformName = "Windows"; extension = ".exe"; #elif UNITY_EDITOR_OSX platformName = "MacOS"; extension = ""; #elif UNITY_EDITOR_LINUX platformName = "Linux"; extension = ""; #endif var arcoreimgPath = Path.Combine(packagePath, "Tools~", platformName, "arcoreimg" + extension); #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX SetExecutablePermission(arcoreimgPath); #endif var startInfo = new Diag.ProcessStartInfo(); startInfo.WindowStyle = Diag.ProcessWindowStyle.Hidden; startInfo.FileName = arcoreimgPath; // This file must have the .imgdb extension (the tool adds it otherwise) var outputDbPath = ARCoreImageTrackingProvider.GetPathForLibrary(imageLib); if (File.Exists(outputDbPath)) { File.Delete(outputDbPath); } startInfo.Arguments = string.Format( "build-db --input_image_list_path={0} --output_db_path={1}", $"\"{inputImageListPath}\"", $"\"{outputDbPath}\""); startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.CreateNoWindow = true; var process = new Diag.Process(); process.StartInfo = startInfo; process.EnableRaisingEvents = true; var stdout = new StringBuilder(); var stderr = new StringBuilder(); process.OutputDataReceived += (sender, args) => stdout.Append(args.Data.ToString()); process.ErrorDataReceived += (sender, args) => stderr.Append(args.Data.ToString()); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); process.CancelOutputRead(); process.CancelErrorRead(); if (!File.Exists(outputDbPath)) { throw new BuildFailedException(string.Format( "Failed to generate image database. Output from arcoreimg:\n\nstdout:\n{0}\n====\n\nstderr:\n{1}\n====", stdout.ToString(), stderr.ToString())); } } catch { Debug.LogErrorFormat("Failed to generated ARCore reference image library '{0}'", imageLib.name); throw; } finally { Directory.Delete(tempDirectory, true); } } } catch { RemoveGeneratedStreamingAssets(); throw; } }