I'm writing an AIR app that launches a C# console application and they need to communicate. I'd like to use standard input/standard output for this, however I can't seem to get it to work.
When the C# app gets input from standard input it's supposed to send it back via standard output, and if it receives "exit" then it quits. I can test this from the command line and it works correctly. When I send a string from AIR, I get no response from the C# app.
I'm sending an argument when I launch the C# app, and I do get a response from that, so my AIR app is at least able to receive messages from standard output, it's just standard input that is not working. When I send a message from AIR via standardInput I get a progress event with bytesLoaded = 3 when I send the keycode, and bytesLoaded = 5 when I send the "exit" command.
Here is the C# code:
static void Main(string[] args)
{
if (args.Length > 0)
{
Console.WriteLine(args[0]);
}
while (true)
{
string incoming = Console.ReadLine();
string outgoing = "received: " + incoming;
Console.WriteLine(outgoing);
if (incoming == "exit")
return;
}
}
And here is the AS3 code:
private function init(e:Event=null):void {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onAppClose);
var info:NativeProcessStartupInfo = new NativeProcessStartupInfo();
var file:File = File.applicationDirectory.resolvePath("test.exe");
info.executable = file;
process = new NativeProcess();
info.arguments.push("native process started");
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(ProgressEvent.STANDARD_INPUT_PROGRESS, onInputProgress);
process.addEventListener(Event.STANDARD_OUTPUT_CLOSE, onOutputClose);
process.addEventListener(Event.STANDARD_ERROR_CLOSE, onErrorClose);
process.addEventListener(IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, onIOError);
process.addEventListener(IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
process.start(info);
}
private function onKeyUp(e:KeyboardEvent):void {
if (e.keyCode == Keyboard.ESCAPE)
process.standardInput.writeUTFBytes("exit\n");
else {
var msg:String = e.keyCode + "\n";
process.standardInput.writeUTFBytes(msg);
}
}
private function onOutputData(e:ProgressEvent):void {
var data:String = process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable);
trace("Got: ", data);
}
I encountered this issue a few months back but I never resolved it as I just used command line args instead. I have just returned to it though as I am keen to find out know what's going on.
I have now found that targeting .NET 3.5 or earlier makes it work as expected for me. Switch back to to v4.0 and I get nothing on stdin. I'm not exactly sure where the issue lies, but if you can get by with v3.5 then it might be a solution for you.
In case anyone else besides me still use Adobe AIR with C# console apps, here's a solution to the problem:
Just like #tom-makin points out in the linked answer, you need to create another console app that runs on .NET 3.5, which then opens your newer .NET console app and passes input to it. Here's my take on such an app:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace StdInPiper
{
class Program
{
static void Main(string[] args)
{
// Remove the first arg from args, containing the newer .NET exePath.
string exePath = args[0];
var tempArgs = new List<string>(args);
tempArgs.RemoveAt(0);
string argsLine = "";
foreach (string arg in tempArgs)
{
argsLine = argsLine + " " + arg;
}
argsLine = argsLine.Trim();
var process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.Arguments = argsLine;
process.StartInfo.FileName = exePath;
process.OutputDataReceived += (sender, eventArgs) =>
{
Console.Write(eventArgs.Data);
};
process.ErrorDataReceived += (sender, eventArgs) =>
{
Console.Error.Write(eventArgs.Data);
};
process.Exited += (sender, eventArgs) =>
{
process.CancelOutputRead();
process.CancelErrorRead();
Environment.Exit(Environment.ExitCode);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
while (true)
{
Thread.Sleep(20);
string line = Console.ReadLine();
if (line != null)
{
process.StandardInput.WriteLine(line);
}
}
}
}
}
Related
I just asked for the Input and now I have to ask for the Output. This already worked, but apparently I changed something important.
I want to read the Output of an SqlPlus Process. The reading itself works, but then it exits further Execution.
I am using DI, but it doesn´t work within a single class either.
Program.cs:
builder.Services.AddScoped<IExecuter,ShellExecuter>();
ShellExecuter.cs:
private List<string> _commands = new List<string>();
private Process _process;
private ProcessStartInfo _startInfo;
public ShellExecuter(){
_startInfo = new ProcessStartInfo();
_startInfo.WorkingDirectory = Path.GetTempPath();
_startInfo.FileName = "sqlplus.exe";
_startInfo.UseShellExecute = false;
_startInfo.RedirectStandardOutput = true;
_startInfo.RedirectStandardError = true;
_startInfo.RedirectStandardInput = true;
_startInfo.CreateNoWindow = true;
_process = new Process();
}
public void Start()
{
_startInfo.Arguments = $"-s user/pass#db";
_process.StartInfo = _startInfo;
// _process.EnableRaisingEvents = true;
_process.Start();
_process.ErrorDataReceived += (sender, args) =>
{
System.Diagnostics.Debug.WriteLine("Error: " + args.Data);
};
process.Exited += new System.EventHandler(Exited);
}
...Methods to add to _commands and Write them.
public string Output()
{
string line = "";
while (!_process.StandardOutput.EndOfStream)
{
line += _process.StandardOutput.ReadLine();
System.Diagnostics.Debug.WriteLine("Output: " + line);
}
}
HomeController.cs:
public IActionResult Index(IExecuter exec)
{
exec.Start();
exec.AddCommand(" create or replace view testview(ID) as select ID from
MyUSER;");
exec.Execute();
var output = exec.Output();
return Content(output);
}
So, when I run this it properly creates the View and goes into the Output loop. However, after I get the "Output: View created.", it will take ~1s and then I will get the message "The Thread xxxxx has exited with Code 0"
I am not sure if this exit is about the Process or the ShellExecuter, but I don´t get out of the While Loop anymore and the Debugger does not show the Buttons to jump to the next Line anymore. Nor does the Website update.
What do I overlook here? It already worked...
In order to read the output you need to attach to the event like this
_process.OutputDataReceived += new DataReceivedEventHandler(DataReceived);
with a method like this
public StringBuilder Output = new StringBuilder();
void DataReceived(object sender, DataReceivedEventArgs e)
{
Output.AppendLine(e.Data);
}
then also add this
_process.Start();
_process.WaitForExit(); //very important!
then you can call
var output = exec.Output.ToString();
I've got a tricky issue with a console app, from which I'm trying to redirect StandardInput, StandardOutput and StandardError.
I've got a working solution for other console app - that's not a new thing for me. But this app seems to have something special, which is making impossible to redirect all outputs with a standard approach.
Console app works like this:
directly after startup writes a few lines and waits for user input
no matter what input is - console app is showing some output and again wait for new input
console app never ends, it has to be closed
I've tried already solutions based on:
StandardOutput/Error.ReadToEnd()
taki care of OutputDataReceived & ErrorDataReceived with read line by line with ReadLine
reading by char
waiting for the end of process (which is not ending, so I'm running into a deadlock)
to start console app in a preloaded cmd.exe and grab this (StandardOutput stopped to show just after launch of this console app)
to manually flush input
All the time I had completely no output and no error stream from console app - nothing.
After a multitude attempts I've discovered, that I can receive StandardOutput only when I'll close StandardInput after programatically inputting the data.
But in this case, console app is going wild, falling into loop of writing few lines to StandardOutput as on start-up, which makes final output big and full of garbages.
With MedallionShell library I'm able to try to gracefully kill it with Ctrl+C, but this solution is still far from acceptable, because:
sometimes console app will produce so much garbages before I will be able to kill it, that it crashes my app
even if this won't crash, searching for expected output in a lot of garbages is nasty and tragically slows down automatization (6000 records in... 15 minutes)
I'm unable to provide more than one input at a time, so I have to start console app just to receive one output, close and start again for another output
I've got no sources for that console app, so I'm even not able to recreate the issue or fix it - it's some very legacy app at my company, which I'm trying to make at least a bit automatic...
Code, with which I've got at least anything now (with MediallionShell):
var command = Command.Run(Environment.CurrentDirectory + #"\console_app.exe");
command.StandardInput.WriteLine("expected_input");
command.StandardInput.Close(); // without that I'll never receive any output or error stream from this stubborn console app
command.TrySignalAsync(CommandSignal.ControlC); // attempt to kill gracefully, not always successfull...
var result = command.Result;
textBox1.AppendText(String.Join(Environment.NewLine, command.GetOutputAndErrorLines().ToArray().Take(10))); // trying to get rid of garbages
command.Kill(); // additional kill attempt if Ctrl+C didn't help, sometimes even this fails
Any help will be appreciated, I'm also still searching for solution and now I'm checking this one: PostMessage not working with console window whose output is redirected and read asynchronously but author there had an output and I don't...
You haven't provided a sample Console program to test with, but something like the following may work:
Create a Console project (Console (.NET Framework)) - used for testing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTestApp
{
class Program
{
static void Main(string[] args)
{
//prompt for input - 1st prompt
Console.Write("Please enter filename: ");
string filename = Console.ReadLine();
if (System.IO.File.Exists(filename))
{
Console.WriteLine("'" + filename + "' exists.");
}
else
{
Console.Error.WriteLine("'" + filename + "' doesn't exist.");
}
//prompt for input - 2nd prompt
Console.Write("Would you like to exit? ");
string answer = Console.ReadLine();
Console.WriteLine("Your answer was: " + answer);
Console.WriteLine("Operation complete.");
}
}
}
Then, create a Windows Forms project Windows Forms (.NET Framework) and run one of the following:
Option 1:
private void RunCmd(string exePath, string arguments = null)
{
//create new instance
ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments);
startInfo.Arguments = arguments; //arguments
startInfo.CreateNoWindow = true; //don't create a window
startInfo.RedirectStandardError = true; //redirect standard error
startInfo.RedirectStandardOutput = true; //redirect standard output
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false; //if true, uses 'ShellExecute'; if false, uses 'CreateProcess'
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.ErrorDialog = false;
//create new instance
using (Process p = new Process { StartInfo = startInfo, EnableRaisingEvents = true })
{
//subscribe to event and add event handler code
p.ErrorDataReceived += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
//ToDo: add desired code
Debug.WriteLine("Error: " + e.Data);
}
};
//subscribe to event and add event handler code
p.OutputDataReceived += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
//ToDo: add desired code
Debug.WriteLine("Output: " + e.Data);
}
};
p.Start(); //start
p.BeginErrorReadLine(); //begin async reading for standard error
p.BeginOutputReadLine(); //begin async reading for standard output
using (StreamWriter sw = p.StandardInput)
{
//provide values for each input prompt
//ToDo: add values for each input prompt - changing the for loop as necessary
for (int i = 0; i < 2; i++)
{
if (i == 0)
sw.WriteLine(#"C:\Temp\Test1.txt"); //1st prompt
else if (i == 1)
sw.WriteLine("Yes"); //2nd prompt
else
break; //exit
}
}
//waits until the process is finished before continuing
p.WaitForExit();
}
}
Option 2:
private void RunCmd(string exePath, string arguments = null)
{
//create new instance
ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments);
startInfo.Arguments = arguments; //arguments
startInfo.CreateNoWindow = true; //don't create a window
startInfo.RedirectStandardError = true; //redirect standard error
startInfo.RedirectStandardOutput = true; //redirect standard output
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false; //if true, uses 'ShellExecute'; if false, uses 'CreateProcess'
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.ErrorDialog = false;
//create new instance
using (Process p = new Process { StartInfo = startInfo, EnableRaisingEvents = true })
{
//subscribe to event and add event handler code
p.ErrorDataReceived += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
//ToDo: add desired code
Debug.WriteLine("Error: " + e.Data);
}
};
//subscribe to event and add event handler code
p.OutputDataReceived += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
//ToDo: add desired code
Debug.WriteLine("Output: " + e.Data);
}
};
p.Start(); //start
p.BeginErrorReadLine(); //begin async reading for standard error
p.BeginOutputReadLine(); //begin async reading for standard output
using (StreamWriter sw = p.StandardInput)
{
//provide values for each input prompt
//ToDo: add values for each input prompt - changing the for loop as necessary
sw.WriteLine(#"C:\Temp\Test1.txt"); //1st prompt
sw.WriteLine("Yes"); //2nd prompt
}
//waits until the process is finished before continuing
p.WaitForExit();
}
}
Option 3:
Note: This one is modified from here.
private void RunCmd(string exePath, string arguments = null)
{
//create new instance
ProcessStartInfo startInfo = new ProcessStartInfo(exePath, arguments);
startInfo.Arguments = arguments; //arguments
startInfo.CreateNoWindow = true; //don't create a window
startInfo.RedirectStandardError = true; //redirect standard error
startInfo.RedirectStandardOutput = true; //redirect standard output
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false; //if true, uses 'ShellExecute'; if false, uses 'CreateProcess'
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.ErrorDialog = false;
//create new instance
using (Process p = new Process { StartInfo = startInfo, EnableRaisingEvents = true })
{
p.Start(); //start
Read(p.StandardOutput);
Read(p.StandardError);
using (StreamWriter sw = p.StandardInput)
{
//provide values for each input prompt
//ToDo: add values for each input prompt - changing the for loop as necessary
sw.WriteLine(#"C:\Temp\Test1.txt"); //1st prompt
sw.WriteLine("Yes"); //2nd prompt
}
//waits until the process is finished before continuing
p.WaitForExit();
}
}
private static void Read(StreamReader reader)
{
new System.Threading.Thread(() =>
{
while (true)
{
int current;
while ((current = reader.Read()) >= 0)
Console.Write((char)current);
}
}).Start();
}
I have a console application and try to use it in C# Asp.Net Core 3.1 WebApi application. The code I am using is as follow:
Create process
Process process;
process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = executable;
process.Start();
Then I keep using the following code to send command to the console application and read the output
process.StandardInput.WriteLine(argument);
string output = string.Empty;
do
{
Thread.Sleep(50);
output = process.StandardOutput.ReadLine();
} while (output == null);
The result is, for the first a few commands, I can get the result from ReadLine function correctly. However, after a few commands, I keep getting null and the whole application stuck at the while loop.
I ran the console application in console and send commands one by one that feed into the second step and all of them can return correct result and print the results in the console as expected.
Can anyone help what could be wrong? Thank you
i just created the solution with your aproach and everything is working correctly. I would advise you to use rather await Task.Delay(50) than Thread.Sleep(50) So having two such console application. Firstly the application i will want to call (i am calling it "External" one:
static void Main(string[] args)
{
string key = String.Empty;
do
{
key = Console.ReadLine();
Console.WriteLine($"{key} was pressed in external program");
} while (key != "q");
}
and the application that is calling this method:
static async Task Main(string[] args)
{
using (Process process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = #"[path_to_the_previous_console_app]\TestConsoleAppExternal.exe";
process.Start();
Console.WriteLine("Write some key");
string key = String.Empty;
do
{
key = Console.ReadLine();
await Interact(process, key);
} while (key != "q");
}
}
static async Task Interact(Process process, string argument)
{
process.StandardInput.WriteLine(argument);
string output = string.Empty;
do
{
await Task.Delay(50);
output = process.StandardOutput.ReadLine();
} while (output == null);
Console.WriteLine($"{argument} was pressed from Main process and readed output was: '{output}' ");
}
And everything works as designed. What scenario exactly you want to achieve? What kind of application are you calling? Maybe this is the difference?
I've a problem in my project. I would like to launch a process, 7z.exe (console version).
I've tried three different things:
Process.StandardOutput.ReadToEnd();
OutputDataReceived & BeginOutputReadLine
StreamWriter
Nothing works. It always "wait" for the end of the process to show what i want.
I don't have any code to put, just if you want my code with one of the things listed upthere. Thanks.
Edit:
My code:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
this.sr = process.StandardOutput;
while (!sr.EndOfStream)
{
String s = sr.ReadLine();
if (s != "")
{
System.Console.WriteLine(DateTime.Now + " - " + s);
}
}
Or
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler(recieve);
process.StartInfo.CreateNoWindow = true;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
public void recieve(object e, DataReceivedEventArgs outLine)
{
System.Console.WriteLine(DateTime.Now + " - " + outLine.Data);
}
Or
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = p.StandardOutput.ReadToEnd();
process.WaitForExit();
Where "process" is my pre-made Process
Ok i know why it doesn't works properly: 7z.exe is the bug: it display a percent loading in console, and it sends information only when the current file is finished. In extraction for example, it works fine :). I will search for another way to use 7z functions without 7z.exe (maybe with 7za.exe or with some DLL). Thanks to all.
To answer to the question, OuputDataRecieved event works fine !
Take a look at this page, it looks this is the solution for you: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline.aspx and http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
[Edit]
This is a working example:
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = #"C:\Program Files (x86)\gnuwin32\bin\ls.exe";
p.StartInfo.Arguments = "-R C:\\";
p.OutputDataReceived += new DataReceivedEventHandler((s, e) =>
{
Console.WriteLine(e.Data);
});
p.ErrorDataReceived += new DataReceivedEventHandler((s, e) =>
{
Console.WriteLine(e.Data);
});
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
Btw, ls -R C:\ lists all files from the root of C: recursively. These are a lot of files, and I'm sure it isn't done when the first results show up in the screen.
There is a possibility 7zip holds the output before showing it. I'm not sure what params you give to the proces.
To correctly handle output and/or error redirection you must also redirect input.
It seem to be feature/bug in runtime of the external application youre starting and from what I have seen so far, it is not mentioned anywhere else.
Example usage:
Process p = new Process(...);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true; // Is a MUST!
p.EnableRaisingEvents = true;
p.OutputDataReceived += OutputDataReceived;
p.ErrorDataReceived += ErrorDataReceived;
Process.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.OutputDataReceived -= OutputDataReceived;
p.ErrorDataReceived -= ErrorDataReceived;
...
void OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// Process line provided in e.Data
}
void ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
// Process line provided in e.Data
}
I don't know if anyone is still looking for a solution to this, but it has come up several times for me because I'm writing a tool in Unity in support of some games and due to the limited interoperability of certain systems with mono (like PIA for reading text from Word, for example), I often have to write OS-specific (sometimes Windows, sometimes MacOS) executables and launch them from Process.Start().
The problem is, when you launch an executable like this it's going to fire up in another thread that blocks your main app, causing a hang. If you want to provide useful feedback to your users during this time beyond the spinning icons conjured up by your respective OS, then you're kind of screwed. Using a stream won't work because the thread is still blocked until execution finishes.
The solution I've hit on, which might seem extreme for some people but I find works quite well for me, is to use sockets and multithreading to set up reliable synchronous comms between the two apps. Of course, this only works if you are authoring both apps. If not, I think you are out of luck. ... I would like to see if it works with just multithreading using a traditional stream approach, so if someone would like to try that and post the results here that would be great.
Anyway, here's the solution currently working for me:
In the main, or calling app, I do something like this:
/// <summary>
/// Handles the OK button click.
/// </summary>
private void HandleOKButtonClick() {
string executableFolder = "";
#if UNITY_EDITOR
executableFolder = Path.Combine(Application.dataPath, "../../../../build/Include/Executables");
#else
executableFolder = Path.Combine(Application.dataPath, "Include/Executables");
#endif
EstablishSocketServer();
var proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = Path.Combine(executableFolder, "WordConverter.exe"),
Arguments = locationField.value + " " + _ipAddress.ToString() + " " + SOCKET_PORT.ToString(),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
Here's where I establish the socket server:
/// <summary>
/// Establishes a socket server for communication with each chapter build script so we can get progress updates.
/// </summary>
private void EstablishSocketServer() {
//_dialog.SetMessage("Establishing socket connection for updates. \n");
TearDownSocketServer();
Thread currentThread;
_ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
_listener = new TcpListener(_ipAddress, SOCKET_PORT);
_listener.Start();
UnityEngine.Debug.Log("Server mounted, listening to port " + SOCKET_PORT);
_builderCommThreads = new List<Thread>();
for (int i = 0; i < 1; i++) {
currentThread = new Thread(new ThreadStart(HandleIncomingSocketMessage));
_builderCommThreads.Add(currentThread);
currentThread.Start();
}
}
/// <summary>
/// Tears down socket server.
/// </summary>
private void TearDownSocketServer() {
_builderCommThreads = null;
_ipAddress = null;
_listener = null;
}
Here's my socket handler for the thread... note that you will have to create multiple threads in some cases; that's why I have that _builderCommThreads List in there (I ported it from code elsewhere where I was doing something similar but calling multiple instances in a row):
/// <summary>
/// Handles the incoming socket message.
/// </summary>
private void HandleIncomingSocketMessage() {
if (_listener == null) return;
while (true) {
Socket soc = _listener.AcceptSocket();
//soc.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000);
NetworkStream s = null;
StreamReader sr = null;
StreamWriter sw = null;
bool reading = true;
if (soc == null) break;
UnityEngine.Debug.Log("Connected: " + soc.RemoteEndPoint);
try {
s = new NetworkStream(soc);
sr = new StreamReader(s, Encoding.Unicode);
sw = new StreamWriter(s, Encoding.Unicode);
sw.AutoFlush = true; // enable automatic flushing
while (reading == true) {
string line = sr.ReadLine();
if (line != null) {
//UnityEngine.Debug.Log("SOCKET MESSAGE: " + line);
UnityEngine.Debug.Log(line);
lock (_threadLock) {
// Do stuff with your messages here
}
}
}
//
} catch (Exception e) {
if (s != null) s.Close();
if (soc != null) soc.Close();
UnityEngine.Debug.Log(e.Message);
//return;
} finally {
//
if (s != null) s.Close();
if (soc != null) soc.Close();
UnityEngine.Debug.Log("Disconnected: " + soc.RemoteEndPoint);
}
}
return;
}
Of course, you'll need to declare some stuff up at the top:
private TcpListener _listener = null;
private IPAddress _ipAddress = null;
private List<Thread> _builderCommThreads = null;
private System.Object _threadLock = new System.Object();
...then in the invoked executable, set up the other end (I used statics in this case, you can use what ever you want):
private static TcpClient _client = null;
private static Stream _s = null;
private static StreamReader _sr = null;
private static StreamWriter _sw = null;
private static string _ipAddress = "";
private static int _port = 0;
private static System.Object _threadLock = new System.Object();
/// <summary>
/// Main method.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args) {
try {
if (args.Length == 3) {
_ipAddress = args[1];
_port = Convert.ToInt32(args[2]);
EstablishSocketClient();
}
// Do stuff here
if (args.Length == 3) Cleanup();
} catch (Exception exception) {
// Handle stuff here
if (args.Length == 3) Cleanup();
}
}
/// <summary>
/// Establishes the socket client.
/// </summary>
private static void EstablishSocketClient() {
_client = new TcpClient(_ipAddress, _port);
try {
_s = _client.GetStream();
_sr = new StreamReader(_s, Encoding.Unicode);
_sw = new StreamWriter(_s, Encoding.Unicode);
_sw.AutoFlush = true;
} catch (Exception e) {
Cleanup();
}
}
/// <summary>
/// Clean up this instance.
/// </summary>
private static void Cleanup() {
_s.Close();
_client.Close();
_client = null;
_s = null;
_sr = null;
_sw = null;
}
/// <summary>
/// Logs a message for output.
/// </summary>
/// <param name="message"></param>
private static void Log(string message) {
if (_sw != null) {
_sw.WriteLine(message);
} else {
Console.Out.WriteLine(message);
}
}
...I'm using this to launch a command line tool on Windows that uses the PIA stuff to pull text out of a Word doc. I tried PIA the .dlls in Unity, but ran into interop issues with mono. I'm also using it on MacOS to invoke shell scripts that launch additional Unity instances in batchmode and run editor scripts in those instances that talk back to the tool over this socket connection. It's great, because I can now send feedback to the user, debug, monitor and respond to specific steps in the process, et cetera, et cetera.
HTH
The problem is caused by calling the Process.WaitForExit method. What this does, according to the documentation, is:
Sets the period of time to wait for the associated process to exit,
and blocks the current thread of execution until the time has elapsed
or the process has exited. To avoid blocking the current thread, use
the Exited event.
So, to prevent the thread blocking until the process has exited, wire up the Process.Exited event handler of the Process object, as below. The Exited event can occur only if the value of the EnableRaisingEvents property is true.
process.EnableRaisingEvents = true;
process.Exited += Proc_Exited;
private void Proc_Exited(object sender, EventArgs e)
{
// Code to handle process exit
}
Done this way, you will be able to get the output of your process, while it is still running, via the Process.OutputDataReceived event as you currently do. (PS - the code example on that event page also makes the mistake of using Process.WaitForExit.)
Another note is that you need to ensure your Process object is not cleaned up before your Exited method can fire. If your Process is initialized in a using statement, this might be a problem.
I have used the CmdProcessor class described here on several projects with much success. It looks a bit daunting at first but is very easy to use.
Windows treats pipes and consoles differently. Pipes are buffered, consoles are not. RedirectStandardOutput connects a pipe. There are only two solutions.
Change the console app to flush its buffer after every write
Write a shim to fake a console per https://www.codeproject.com/Articles/16163/Real-Time-Console-Output-Redirection
Note that RTConsole does not handle STDERR which suffers the same problem.
Thanks to https://stackoverflow.com/users/4139809/jeremy-lakeman for sharing this information with me in relation to another question.
Try this.
Process notePad = new Process();
notePad.StartInfo.FileName = "7z.exe";
notePad.StartInfo.RedirectStandardOutput = true;
notePad.StartInfo.UseShellExecute = false;
notePad.Start();
StreamReader s = notePad.StandardOutput;
String output= s.ReadToEnd();
notePad.WaitForExit();
Let the above be in a thread.
Now for updating the output to UI,you can use a timer with two lines
Console.Clear();
Console.WriteLine(output);
This may help you
How do I invoke a console application from my .NET application and capture all the output generated in the console?
(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)
This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();
This is bit improvement over accepted answer from #mdb. Specifically, we also capture error output of the process. Additionally, we capture these outputs through events because ReadToEnd() doesn't work if you want to capture both error and regular output. It took me while to make this work because it actually also requires BeginxxxReadLine() calls after Start().
Asynchronous way:
using System.Diagnostics;
Process process = new Process();
void LaunchProcess()
{
process.EnableRaisingEvents = true;
process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);
process.Exited += new System.EventHandler(process_Exited);
process.StartInfo.FileName = "some.exe";
process.StartInfo.Arguments = "param1 param2";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
//below line is optional if we want a blocking call
//process.WaitForExit();
}
void process_Exited(object sender, EventArgs e)
{
Console.WriteLine(string.Format("process exited with code {0}\n", process.ExitCode.ToString()));
}
void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data + "\n");
}
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data + "\n");
}
Use ProcessStartInfo.RedirectStandardOutput to redirect the output when creating your console process.
Then you can use Process.StandardOutput to read the program output.
The second link has a sample code how to do it.
ConsoleAppLauncher is an open source library made specifically to answer that question. It captures all the output generated in the console and provides simple interface to start and close console application.
The ConsoleOutput event is fired every time when a new line is written by the console to standard/error output. The lines are queued and guaranteed to follow the output order.
Also available as NuGet package.
Sample call to get full console output:
// Run simplest shell command and return its output.
public static string GetWindowsVersion()
{
return ConsoleApp.Run("cmd", "/c ver").Output.Trim();
}
Sample with live feedback:
// Run ping.exe asynchronously and return roundtrip times back to the caller in a callback
public static void PingUrl(string url, Action<string> replyHandler)
{
var regex = new Regex("(time=|Average = )(?<time>.*?ms)", RegexOptions.Compiled);
var app = new ConsoleApp("ping", url);
app.ConsoleOutput += (o, args) =>
{
var match = regex.Match(args.Line);
if (match.Success)
{
var roundtripTime = match.Groups["time"].Value;
replyHandler(roundtripTime);
}
};
app.Run();
}
I've added a number of helper methods to the O2 Platform (Open Source project) which allow you easily script an interaction with another process via the console output and input (see http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs)
Also useful for you might be the API that allows the viewing of the console output of the current process (in an existing control or popup window). See this blog post for more details: http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (this blog also contains details of how to consume the console output of new processes)
I made a reactive version that accepts callbacks for stdOut and StdErr.
onStdOut and onStdErr are called asynchronously,
as soon as data arrives (before the process exits).
public static Int32 RunProcess(String path,
String args,
Action<String> onStdOut = null,
Action<String> onStdErr = null)
{
var readStdOut = onStdOut != null;
var readStdErr = onStdErr != null;
var process = new Process
{
StartInfo =
{
FileName = path,
Arguments = args,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = readStdOut,
RedirectStandardError = readStdErr,
}
};
process.Start();
if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));
if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));
process.WaitForExit();
return process.ExitCode;
}
private static void ReadStream(TextReader textReader, Action<String> callback)
{
while (true)
{
var line = textReader.ReadLine();
if (line == null)
break;
callback(line);
}
}
Example usage
The following will run executable with args and print
stdOut in white
stdErr in red
to the console.
RunProcess(
executable,
args,
s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },
s => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(s); }
);
From PythonTR - Python Programcıları Derneği, e-kitap, örnek:
Process p = new Process(); // Create new object
p.StartInfo.UseShellExecute = false; // Do not use shell
p.StartInfo.RedirectStandardOutput = true; // Redirect output
p.StartInfo.FileName = "c:\\python26\\python.exe"; // Path of our Python compiler
p.StartInfo.Arguments = "c:\\python26\\Hello_C_Python.py"; // Path of the .py to be executed
Added process.StartInfo.**CreateNoWindow** = true; and timeout.
private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)
{
using (Process process = new Process())
{
process.StartInfo.FileName = exeName;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
output = process.StandardOutput.ReadToEnd();
bool exited = process.WaitForExit(timeoutMilliseconds);
if (exited)
{
exitCode = process.ExitCode;
}
else
{
exitCode = -1;
}
}
}