C#: Calling a php script and beeing able to stop it - c#

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

Related

Process() get blocked even with WaitForExit()?

Working on a project. In the code, we need to run powershell script and then get its output. In order to do this, I use the Process():
private int RunProcess(string FileName, string Arguments, out string result)
{
int exitCode = -1;
result = string.Empty;
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = FileName;
p.StartInfo.Arguments = Arguments;
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// Read the output stream first and then wait.
result = p.StandardOutput.ReadToEnd();
// Wait at most 10 minutes
p.WaitForExit(10 * 60 * 1000);
exitCode = p.ExitCode;
return exitCode;
}
and call it like this:
RunProcess("Powershell.exe", arguments, out sPSResult);
This works fine on most computers. However, on some, for some unknow reason, the RunProcess() never return, even we use p.WaitForExit(10 * 60 * 1000) .
Anyone knows why? or see this before? Is it because somewhere is blocked in the windows even WaitForExit is used?
Thanks
Are you sure your code even reaches WaitForExit and is not hanging on ReadToEnd? My guess it's getting stuck there because it can't read all of the output. Also for details on how to deal with reading standard and error outputs from child processes correctly, see:
ProcessStartInfo hanging on "WaitForExit"? Why?

Process WaitForExit() never end (cmd openfiles)

this code works fine on my test-system (Copy of the original Windows-Server 2008 R2)
private string _getNetFiles()
{
// prepare execution process
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c openfiles /query /Fo list");
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardError = true;
processStartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(437);
processStartInfo.RedirectStandardOutput = true;
// execute
Process process = Process.Start(processStartInfo);
process.WaitForExit();
// read outputs
string stdOutput = process.StandardOutput.ReadToEnd();
string stdError = process.StandardError.ReadToEnd();
return stdOutput;
}
On the original system:
I see the "cmd.exe /c openfiles /query /Fo list" task in the Task-Manger, but this task never end (process.WaitForExit() process never end ).
Cmd on the original system: openfiles /query /fo list works also fine!
Where can the problem be?
regards raiserle
edit:
I can stop the process with task-manager.
The stdOutput is correct. Why don't end the cmd-taks.
The child process is either waiting for input or for its output to be read. The pipe buffers are not infinitely big. You need to constantly drain both standard output as well as standard error.
Get Values from Process StandardOutput looks reasonable. https://stackoverflow.com/a/24084220/122718 documents how to safely read both streams.
Also note Visual Basic Capture output of cmd as well as everything that Hans Passant says on this topic.
Using the Process class without output redirection is quite tricky and poorly documented.

command redirection issue

here is my code
//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = "ffmpeg.exe";
//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = "-i " + videoName;
pProcess.StartInfo.UseShellExecute = false;
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;
//Start the process
pProcess.Start();
//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();
//Wait for process to finish
pProcess.WaitForExit();
The command works, but strOutput string is empty, results are shown within the console. Am I missing something here?
It's possible the program is writing its output to StandardError instead of StandardOutput. Try using .RedirectStandardError = true and then .pProcess.StandardError.ReadToEnd() to capture that output.
If you need the possibility of capturing both standard error and standard out in (roughly) the proper interleave, you will likely need to use the async versions with callbacks on OutputDataReceived and ErrorDataReceived and using BeginOutput/ErrorReadLine.
Try to capture Std Error too as on any event of error, it will be used instead.
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardError = true;
pProcess.StartInfo.RedirectStandardOutput = true;
//Start the process
pProcess.Start();
//Wait for process to finish
pProcess.WaitForExit();
//Get program output
string strError = pProcess.StandardError.ReadToEnd();
string strOutput = pProcess.StandardOutput.ReadToEnd();
I just wonder why you wait for exit WaitForExit after reading the output, it should be in reversed order as your app may dump more until it finally completes the ops

C#: get external shell command result line by line

I am writing a C# winform application that starts a second process to execute shell commands like "dir" and "ping". I redirect the second process's output so my app can receive the command result. It roughly works fine.
The only problem is my winform app receives the command line output as a whole instead of line by line. For example, it has to wait for the external "ping" command to finish (which takes many seconds or longer) and then receives the whole output (many lines) at once.
What I want is the app receives the cmdline output in real-time, i.e. by lines not by block. Is this doable?
I am using this code to read the output:
while ((result = proc.StandardOutput.ReadLine()) != null)
But it does not work the way I expected.
Thanks in advance.
EDIT: here is the code I am using:
System.Diagnostics.ProcessStartInfo procStartInfo = new
System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// The following commands are needed to redirect the standard output.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result;
try {
while ((result = proc.StandardOutput.ReadLine()) != null)
{
AppendRtfText(result+"\n", Brushes.Black);
}
} // here I expect it to update the text box line by line in real time
// but it does not.
Have a look at the example in this msdn article on how to do the reading completly async.
Beyond that I expect your code does to read line by line now but the UI doesn't get any time to repaint (missing Application.DoEvents(); after updating the RTFTextBox
Instead of loop using while ((result = proc.StandardOutput.ReadLine()) != null) you should of using:
...
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
This will start asynchronous reading the lines when they arrives, you then handle the lines read by e.Data in proc_DataReceived handler, since you are use BeginOutputReadline the e.Data will be a string lines.
This could be usefull:
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/8d6cebfc-9b8b-4667-85b5-2b92105cd0b7/
http://www.dotnetperls.com/redirectstandardoutput
I had the same issue and got around it with the following. I found that if I had an error in the external app I was getting no output at all using the ReadToEnd() method, so switched to use the line by line streamreader. Will be switching over to use the answer provided by Saa'd though as that looks like the proper way to handle it.
Also found this solution: c# coding convention public/private contexts which provides for error handling at the same time and giving a fuller explanation to the use of externalApp.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
Process externalApp = new Process();
externalApp.StartInfo.FileName = config.ExternalApps + #"\location\DeleteApp.exe";
externalApp.StartInfo.Arguments = Directory.GetCurrentDirectory() + #"\..\..\..\project\argumentsForDeleteApp.xml";
externalApp.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
externalApp.StartInfo.UseShellExecute = false;
externalApp.StartInfo.RedirectStandardOutput = true;
Console.Out.WriteLine(DateTime.UtcNow.ToLocalTime().ToString() +
":###### External app: " + externalApp.StartInfo.FileName + " - START");
externalApp.Start();
using (StreamReader reader = externalApp.StandardOutput)
{
while (!reader.EndOfStream)
{
string result = reader.ReadLine();
Console.Out.WriteLine(result);
}
}
externalApp.WaitForExit();

C# Process - Pause or sleep before completion

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

Categories

Resources