I have a console based c app .
I am executing it from c# silently using Redirecting Standard Output and doing it synchronously which works fine.
Now i want to do it in asynch manner which is giving output like synch manner.
i.e
OutPutDataRecieved event is fired but only after the console app(exe) finishes.OutputDataRecieved event is fired for each line after finish, not instantly as soon as it gets a line in output.
The code for asynch works for CMD.exe etc ,So,I am sure its c based app having problem in output.
FYI:The output in c console is done using printf.
Based on my findings:
I think c console app is not giving output/writing to stdout until it finishes its execution.
I tried setting buffer to null or flushing after every printf but none works.
Any tricks??
Thanks man.That worked like a charm.
I was using setbuf to set buffer null.
Really appreciate efforts of all you guyz.
FOr info of other guyz,this was my c# code which is available on internet forums and SO too.
string command = #"Output.exe";
string arguments = "hellotext";
ProcessStartInfo info = new ProcessStartInfo(command, arguments);
// Redirect the standard output of the process.
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
// Set UseShellExecute to false for redirection
info.UseShellExecute = false;
Process proc = new Process();
proc.StartInfo = info;
proc.EnableRaisingEvents = true;
// Set our event handler to asynchronously read the sort output.
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Exited += new EventHandler(proc_Exited);
proc.Start();
// Start the asynchronous read of the sort output stream. Note this line!
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
Console.WriteLine("Exited (Main)");
}
static void proc_Exited(object sender, EventArgs e)
{
Console.WriteLine("Exited (Event)");
}
static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error: {0}", e.Data);
}
static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output data: {0}", e.Data);
}
You can disable the buffering using setvbuf.
Here is a quick example, if you remove the call to setvbuf then the redirected content is only written once you press enter (waiting on the getchar()). With the setvbuf, the string is written to the redirected stream directly.
int _tmain(int argc, _TCHAR* argv[])
{
setvbuf(stdout, NULL,_IONBF, 0);
printf("Hello");
getchar();
return 0;
}
Related
I am currently working on a C# Program which needs to call a local PHP script and write its output to a file. The problem is, that I need to be able to stop the execution of the script.
First, I tried to call cmd.exe and let cmd write the output to the file which worked fine. But I found out, that killing the cmd process does not stop the php cli.
So I tried to call php directly, redirect its output and write it from the C# code to a file. But here the problem seems to be, that the php cli does not terminate when the script is done. process.WaitForExit() does not return, even when I am sure that the script has been fully executed.
I cannot set a timeout to the WaitForExit(), because depending on the arguments, the script may take 3 minutes or eg. 10 hours.
I do not want to kill just a random php cli, there may be others currently running.
What is the best way to call a local php script from C#, writing its output to a file and beeing able to stop the execution?
Here is my current code:
// Create the process
var process = new System.Diagnostics.Process();
process.EnableRaisingEvents = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "php.exe";
// CreateExportScriptArgument returns something like "file.php arg1 arg2 ..."
process.StartInfo.Arguments = CreateExportScriptArgument(code, this.content, this.options);
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.RedirectStandardOutput = true;
// Start the process or cancel, if the process should not run
if (!this.isRunning) { return; }
this.currentProcess = process;
process.Start();
// Get the output
var output = process.StandardOutput;
// Wait for the process to finish
process.WaitForExit();
this.currentProcess = null;
To kill the process I am using:
// Mark as not running to prevent starting new
this.isRunning = false;
// Kill the process
if (this.currentProcess != null)
{
this.currentProcess.Kill();
}
Thanks for reading!
EDIT
That the cli does not return seems to be not reproducible. When I test a different script (without arguments) it works, probably its the script or the passing of the arguments.
Running my script from cmd works just fine, so the script should not be the problem
EDIT 2
When disabling RedirectStandardOutput, the cli quits. could it be, that I need to read the output, before the process finishes? Or does the process wait, when some kind of buffer is full?
EDIT 3: Problem solved
Thanks to VolkerK, I / we found a solution. The problem was, that WaitForExit() did not get called, when the output is not read (probably due to a full buffer in the standard output). My script wrote much output.
What works for me:
process.Start();
// Get the output
var output = process.StandardOutput;
// Read the input and write to file, live to avoid reading / writing to much at once
using (var file = new StreamWriter("path\\file", false, new UTF8Encoding()))
{
// Read each line
while (!process.HasExited)
{
file.WriteLine(output.ReadLine());
}
// Read the rest
file.Write(output.ReadToEnd());
// flush to file
file.Flush();
}
Since the problem was that the output buffer was full and therefore the php process stalled while waiting to send its output, asynchronously reading the output in the c# program is the solution.
class Program {
protected static /* yeah, yeah, it's only an example */ StringBuilder output;
static void Main(string[] args)
{
// Create the process
var process = new System.Diagnostics.Process();
process.EnableRaisingEvents = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "php.exe";
process.StartInfo.Arguments = "-f path\\test.php mu b 0 0 pgsql://user:pass#x.x.x.x:5432/nominatim";
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.RedirectStandardOutput = true;
output = new StringBuilder();
process.OutputDataReceived += process_OutputDataReceived;
// Start the process
process.Start();
process.BeginOutputReadLine();
// Wait for the process to finish
process.WaitForExit();
Console.WriteLine("test");
// <-- do something with Program.output here -->
Console.ReadKey();
}
static void process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data)) {
// edit: oops the new-line/carriage-return characters are not "in" e.Data.....
// this _might_ be a problem depending on the actual output.
output.Append(e.Data);
output.Append(Environment.NewLine);
}
}
}
see also: https://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline%28v=vs.110%29.aspx
I have a C# GUI from which I run a python script that takes about 2 minutes. Rather than direct the output of the Python script to a file, I'd like to have GUI show all the print-outs that the Python script makes, say, in a text box, as the process is running. Any solution I've found typically waits for the process to end before redirecting the standard output to the text box, and I'm not sure if I'm searching for a solution correctly. Does anyone have an idea about how to do this? Here's some code for reference:
using (Process proc = new Process())
{
debug_output.AppendText("All debug output will be listed below\n");
string pyFileName = "hello.py";
string args = "arg1";
proc.StartInfo.FileName = "C:\\Python27\\python.exe";
proc.StartInfo.Arguments = string.Format("{0} {1}", pyFileName, args);
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(MyProcOutputHandler);
proc.Start();
proc.BeginOutputReadLine();
while (!proc.HasExited)
{
Application.DoEvents();
}
}
With The following Handler:
private void MyProcOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
if (debug_output.InvokeRequired)
{
debug_output.BeginInvoke(new DataReceivedEventHandler(MyProcOutputHandler), new[] { sendingProcess, outLine });
}
else
{
debug_output.AppendText(outLine.Data);
debug_output.AppendText("\n");
}
}
Console.WriteLine(outLine.Data);
}
As an update, I tried the solution from this post since it looks like the exact same problem, but I still don't get it working. My output ends up in the right place, but only after the whole script is done running. Please help.
I want to execute an application(command line application) from the C#... and I want after executing this application and providing the input to it, I want to parse the output that will result it. Since, it will output many things, and I want to take, just the things that I need it from it...
How can I do that ??
How can I get the output in the c# and then take only the things I need it from it ??
For executing the command line in C#... I'm thinking to use "Jeff MC" way, that he explained it in this thread
How To: Execute command line in C#, get STD OUT results
Thanks alot
There is one more way of getting all the output as events as and when they are output by the other console application cmd_DataReceived gets raised whenever there is output and cmd_Error gets raised whenever there is an error raised in the other application.
If you want to parse the output, probably handling these events is a better way to read output and handle errors in the other application as and when they occur.
using System;
using System.Diagnostics;
namespace InteractWithConsoleApp
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = #"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.bing.com"); //Execute ping bing.com
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output from other process");
Console.WriteLine(e.Data);
}
static void cmd_Error(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error from other process");
Console.WriteLine(e.Data);
}
}
}
I have a Process:
Process pr = new Process();
pr.StartInfo.FileName = #"wput.exe";
pr.StartInfo.Arguments = #"C:\Downloads\ ftp://user:dvm#172.29.200.158/Transfer/Updates/";
pr.StartInfo.RedirectStandardOutput = true;
pr.StartInfo.UseShellExecute = false;
pr.StartInfo.
pr.Start();
string output = pr.StandardOutput.ReadToEnd();
Console.WriteLine("Output:");
Console.WriteLine(output);
Wput is an ftp upload client.
At the moment when I run the process and begin the upload, the app freezes and the console output won't show until the end. I guess the first problem is solvable by using a Thread.
What I want to do is start an upload, have it pause every so often, read whatever output has been generated (use this data do make progress bar etc), and begin again.
What classes/methods should I be looking into?
You can use the OutputDataReceived event to print the output asynchronously. There are a few requirements for this to work:
The event is enabled during asynchronous read operations on StandardOutput. To start asynchronous read operations, you must redirect the StandardOutput stream of a Process, add your event handler to the OutputDataReceived event, and call BeginOutputReadLine. Thereafter, the OutputDataReceived event signals each time the process writes a line to the redirected StandardOutput stream, until the process exits or calls CancelOutputRead.
An example of this working is below. It's just doing a long running operation that also has some output (findstr /lipsn foo * on C:\ -- look for "foo" in any file on the C drive). The Start and BeginOutputReadLine calls are non-blocking, so you can do other things while the console output from your FTP application rolls in.
If you ever want to stop reading from the console, use the CancelOutputRead/CancelErrorRead methods. Also, in the example below, I'm handling both standard output and error output with a single event handler, but you can separate them and deal with them differently if needed.
using System;
using System.Diagnostics;
namespace AsyncConsoleRead
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "findstr.exe";
p.StartInfo.Arguments = "/lipsn foo *";
p.StartInfo.WorkingDirectory = "C:\\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
}
static void OnDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
}
}
The best method would be to use libraries which support FTP, instead of relying on external applications. If you don't need much info from the external application and are not verifying their outputs, then go ahead. Else better use FTP client libs.
May be you would like to see libs/documentations:
http://msdn.microsoft.com/en-us/library/ms229711.aspx
http://www.codeproject.com/KB/IP/ftplib.aspx
http://www.c-sharpcorner.com/uploadfile/danglass/ftpclient12062005053849am/ftpclient.aspx
I'm developing an Windows Forms application that requires me to call a separate program to perform a task. The program is a console application and I need to redirect standard output from the console to a TextBox in my program.
I have no problem executing the program from my application, but I don't know how to redirect the output to my application. I need to capture output while the program is running using events.
The console program isn't meant to stop running until my application stops and the text changes constantly at random intervals. What I'm attempting to do is simply hook output from the console to trigger an event handler which can then be used to update the TextBox.
I am using C# to code the program and using the .NET framework for development. The original application is not a .NET program.
EDIT:
Here's example code of what I'm trying to do. In my final app, I'll replace Console.WriteLine with code to update the TextBox. I tried to set a breakpoint in my event handler, and it isn't even reached.
void Method()
{
var p = new Process();
var path = #"C:\ConsoleApp.exe";
p.StartInfo.FileName = path;
p.StartInfo.UseShellExecute = false;
p.OutputDataReceived += p_OutputDataReceived;
p.Start();
}
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(">>> {0}", e.Data);
}
This works for me:
void RunWithRedirect(string cmdPath)
{
var proc = new Process();
proc.StartInfo.FileName = cmdPath;
// set up output redirection
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.EnableRaisingEvents = true;
proc.StartInfo.CreateNoWindow = true;
// see below for output handler
proc.ErrorDataReceived += proc_DataReceived;
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
// output will be in string e.Data
}
You can use the following code
MemoryStream mem = new MemoryStream(1000);
StreamWriter writer = new StreamWriter(mem);
Console.SetOut(writer);
Assembly assembly = Assembly.LoadFrom(#"C:\ConsoleApp.exe");
assembly.EntryPoint.Invoke(null, null);
writer.Close();
string s = Encoding.Default.GetString(mem.ToArray());
mem.Close();
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)
Thanks to Marc Maxham for his answer that save me time !
As Jon of All Trades notice it, UseShellExecute must be set to false in order to redirect IO streams, otherwise the Start() call throws an InvalidOperationException.
Here is my modification of the code where txtOut is a WPF readonly Textbox
void RunWithRedirect(string cmdargs)
{
var proc = new Process()
{
StartInfo = new ProcessStartInfo("cmd.exe", "/k " + cmdargs)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
},
EnableRaisingEvents = true
};
// see below for output handler
proc.ErrorDataReceived += proc_DataReceived;
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Dispatcher.BeginInvoke(new Action( () => txtOut.Text += (Environment.NewLine + e.Data) ));
}