Program.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. namespace StdioSniffer
  6. {
  7. internal class Program
  8. {
  9. private static void Main(string[] args)
  10. {
  11. var cmd = Environment.GetCommandLineArgs();
  12. var path = Path.GetDirectoryName(cmd[0]);
  13. var file = Path.GetFileNameWithoutExtension(cmd[0]);
  14. var ext = Path.GetExtension(cmd[0]);
  15. var target = Path.Combine(path, $"{file}-real{ext}");
  16. var targetArgs = string.Join(" ", cmd.Skip(1));
  17. var logPath = Path.Combine(path, $"{file}{ext}.stdio-sniff.{DateTime.Now:yyyyMMdd-HHmmss-fff}.log");
  18. using var fs = File.CreateText(logPath);
  19. fs.AutoFlush = true;
  20. fs.WriteLine($"CMDLINE:{targetArgs}");
  21. var process = new Process
  22. {
  23. StartInfo =
  24. {
  25. FileName = target,
  26. Arguments = targetArgs,
  27. UseShellExecute = false,
  28. CreateNoWindow = true,
  29. RedirectStandardError = true,
  30. RedirectStandardInput = true,
  31. RedirectStandardOutput = true
  32. }
  33. };
  34. process.OutputDataReceived += (sender, eventArgs) =>
  35. {
  36. var line = eventArgs.Data;
  37. fs.WriteLine($"STDOUT:{line}");
  38. Console.WriteLine(line);
  39. Console.Out.Flush();
  40. };
  41. process.ErrorDataReceived += (sender, eventArgs) =>
  42. {
  43. var line = eventArgs.Data;
  44. fs.WriteLine($"STDERR:{line}");
  45. Console.Error.WriteLine(line);
  46. Console.Error.Flush();
  47. };
  48. process.Start();
  49. process.BeginErrorReadLine();
  50. process.BeginOutputReadLine();
  51. while (false == process.HasExited)
  52. {
  53. var line = Console.ReadLine();
  54. fs.WriteLine($"STDIN:{line}");
  55. process.StandardInput.WriteLine(line);
  56. process.StandardInput.Flush();
  57. }
  58. }
  59. }
  60. }