I've a method that contains a process that must be stopped in a deadline( ex: 3 seconds) whether it has finished or not, and I don't want to wait if it has finished executing before reaching that dead line.
using Process.WaitForExit(3000) makes the program wait 3s even if the process has stopped before reaching the limit.
One more thing, I'm using process.StandardOutput.ReadToEnd(); to read the execution result, I don't care if it returns null or empty string or whatever if it doesn't finish.
And I guess that timers will cause the same problem.
Any Ideas?
Exited event of your process can be handled for detecting exit time.
WaitForExit returns a Boolean value that indicates your process has reached the timeout before exit or not.
Test this code:
Process proc = new Process();
ProcessStartInfo procInfo = new ProcessStartInfo()
{
FileName = "d:/test.exe",
UseShellExecute = false,
RedirectStandardOutput = true
};
proc.StartInfo = procInfo;
proc.EnableRaisingEvents = true;
proc.Exited += (o, args) =>
{
MessageBox.Show(proc.StandardOutput.ReadToEnd());
};
proc.Start();
if (proc.WaitForExit(3000))
{
MessageBox.Show("YES");
}
else
{
MessageBox.Show("NO");
}
Related
I was trying to wrap a EAP in a Task with following code.
public static async Task<string> Caller()
{
var ret = await RunProgram();
return ret;
}
public static async Task<string> RunProgram()
{
TaskCompletionSource<string> source = new TaskCompletionSource<string>();
var process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "cmd";
process.Exited += (sender, args) =>
{
source.SetResult("hello");
};
process.Start();
return await source.Task;
}
However,the Exited Event never gets fired. Could someone guide me on what am doing wrong here ?
Please note that above code is a prototype, the 'event-not-firing' scenario happens in the real scenario as well.
You need to enable event raising property of the Process
like this
var process = new Process
{
EnableRaisingEvents = true,
StartInfo = new ProcessStartInfo(processPath)
{
RedirectStandardError = true,
UseShellExecute = false
}
};
Without addressing any other issue.
Process.EnableRaisingEvents Property
Gets or sets whether the Exited event should be raised when the
process terminates.
Remarks
The EnableRaisingEvents property indicates whether the component
should be notified when the operating system has shut down a process.
The EnableRaisingEvents property is used in asynchronous processing to
notify your application that a process has exited. To force your
application to synchronously wait for an exit event (which interrupts
processing of the application until the exit event has occurred), use
the WaitForExit method
Example
var p = Process.Start(startInfo);
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(ProcessExited);
When working with processes in .NET, I have become accustomed to the behavior that the exiting of the process will end the output of StandardOutput and StandardError. However, I have found one exe where this does not seem to be the case, and I would like to understand whether and why my assumption is wrong.
Here is code that reproduces the issue I am seeing. It uses a specific version of the Android Debug Bridge executable (available from https://hostr.co/bBxxj7gFfMlW).
// before running, terminate any adb.exe processes on the system
// adb.exe's initial run leaves behind a background daemon that changes the
// behavior of future adb.exe runs
var process = new Process
{
StartInfo =
{
FileName = #"C:\Users\[my user]\Downloads\ADB-1.0.31.zip\adb.exe",
Arguments = "connect 127.0.0.1",
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardInput = false,
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
process.Start();
var tasks = new Task[]
{
Task.Run(() => { process.WaitForExit(); Console.WriteLine("Process exited"); }),
Task.Run(() =>
{
int b;
while ((b = process.StandardOutput.BaseStream.ReadByte()) != -1)
{
Console.WriteLine($"STDOUT: {b} ({(char)b})");
}
Console.WriteLine("STDOUT: DONE");
}),
Task.Run(() =>
{
int b;
while ((b = process.StandardError.BaseStream.ReadByte()) != -1)
{
Console.WriteLine($"STDERR: {b} ({(char)b})");
}
Console.WriteLine("STDERR: DONE");
})
};
Task.WaitAll(tasks);
I would expect to see that the process runs for a bit, produces some output (logged byte-by-byte to console), and then exits. Once the process exits, the tasks that are reading from the stream should get -1 back and exit themselves.
All of this happens, EXCEPT that after the process exits the streams stay open and the reader tasks hang indefinitely on ReadByte().
EDIT:
Did a bit more digging and found some code in the implementation of Process that underscores my expectation that the stream should close when the process dies. In WaitForExit(), if you are asynchronously streaming output using BeginOutputDataReadLine(), the wait call blocks on making sure that the async output readers received EOF (code). If the above example is modified to use:
process.OutputDataReceived += (o, e) => Console.WriteLine(e.Data);
process.BeginOutputReadLine();
instead of having an explicit task that reads bytes from StandardOutput, then the WaitForExit() task never returns (although polling process.HasExited returns false after a while)!
I use ProcessStartInfo to run a console aplication and ProcessStartInfo can read text from the console after the console is closed:
using (Process p = Process.Start(st))
{
//Thread.Sleep(2000);
p.WaitForExit();
using (StreamReader rd = p.StandardOutput)
{
result = rd.ReadToEnd();
p.Close();
String result1 = String.Copy(result);
}
Is there another method to read text from the console while it is open?
You can use the OutputDataReceived of the Process class
string result = string.Empty;
using (Process process = new Process())
{
process.StartInfo = st; // your ProcessStartInfo
StringBuilder resultBuilder = new StringBuilder();
process.OutputDataReceived += (sender, e) =>
{
st.AppendLine(e.Data);
};
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
result = resultBuilder.ToString();
}
You simply add an event handler to the Process's OutputDataReceived event that gets called whenever the process outputs a line.
Then you need to call BeginOutputReadLine() after the process has been started to begin receiving those events.
In this example, I still wait for the process to exit just to complete the code. Of course you don't need to wait, the events occure while the process is running. So you can store your process variable in a member and dispose it later or even subscribe to its Exited event to get informed when the process terminates.
If you want to start another process and wait (with time out) to finish you can use the following (from MSDN).
//Set a time-out value.
int timeOut=5000;
//Get path to system folder.
string sysFolder=
Environment.GetFolderPath(Environment.SpecialFolder.System);
//Create a new process info structure.
ProcessStartInfo pInfo = new ProcessStartInfo();
//Set file name to open.
pInfo.FileName = sysFolder + #"\eula.txt";
//Start the process.
Process p = Process.Start(pInfo);
//Wait for window to finish loading.
p.WaitForInputIdle();
//Wait for the process to exit or time out.
p.WaitForExit(timeOut);
//Check to see if the process is still running.
if (p.HasExited == false)
//Process is still running.
//Test to see if the process is hung up.
if (p.Responding)
//Process was responding; close the main window.
p.CloseMainWindow();
else
//Process was not responding; force the process to close.
p.Kill();
MessageBox.Show("Code continuing...");
If you want to start another process and read its output then you can use the following pattern (from SO)
// 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 = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
How can you combine the two to read all input, not get stuck in deadlock and have a timeout if the running process goes awry?
This technique will hang if the output buffer is filled with more that 4KB of data. A more foolproof method is to register delegates to be notified when something is written to the output stream. I've already suggested this method before in another post:
ProcessStartInfo processInfo = new ProcessStartInfo("Write500Lines.exe");
processInfo.ErrorDialog = false;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
Process proc = Process.Start(processInfo);
// You can pass any delegate that matches the appropriate
// signature to ErrorDataReceived and OutputDataReceived
proc.ErrorDataReceived += (sender, errorLine) => { if (errorLine.Data != null) Trace.WriteLine(errorLine.Data); };
proc.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null) Trace.WriteLine(outputLine.Data); };
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
You don't have to combine the two - the Process class has an event that fires when output is sent to the StandardOutput - OutputDataReceived.
If you subscribe to the event, you will be able to read output as it arrives and in your main program loop you can still timeout.
you can try modifying the first method to something like this
Process p = Process.Start(pInfo);
string output = string.Empty;
Thread t = new Thread(() => output = p.StandardOutput.ReadToEnd() );
t.Start();
//Wait for window to finish loading.
p.WaitForInputIdle();
//Wait for the process to exit or time out.
p.WaitForExit(timeOut);
void OpenWithStartInfo()
{
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe", "Default2.aspx");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process p = Process.Start(startInfo);
p.WaitForInputIdle();
//p.WaitForExit(2);
p.Kill();
}
You could also use the APM, like this:
Define a delegate for the ReadToEnd call:
private delegate string ReadToEndDelegate();
Then use the delegate to call the method like this:
ReadToEndDelegate asyncCall = reader.ReadToEnd;
IAsyncResult asyncResult = asyncCall.BeginInvoke(null, null);
asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10));
asyncCall.EndInvoke(asyncResult);
EDIT: Error handling removed for clarity.
Just add everything from the first example below the WaitForExit() call to the second example.
None of the above answers work for me when dealing with interactive promts. (My command sometimes promts a question to the user and that should also be covered by timeout).
This is my solution.
A disadvantage is that i don't get any output if we run in a timeout.
ReadToEnd() blocks the execution so we have to run it in another thread and kill this thread if the process runs into the specified timeout.
public static Tuple<string, string> ExecuteCommand(string command)
{
// prepare start info
var procStartInfo = new ProcessStartInfo("cmd", "/c " + command)
{
ErrorDialog = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
WorkingDirectory = #"C:\",
CreateNoWindow = true
};
// start process
var proc = new Process {StartInfo = procStartInfo};
proc.Start();
var error = "";
var output = "";
// read stdout and stderr in new thread because it is blocking
Thread readerThread = new(() =>
{
try
{
error = proc.StandardError.ReadToEnd().Trim();
output = proc.StandardOutput.ReadToEnd().Trim();
}
catch (ThreadInterruptedException e)
{
Debug.WriteLine("Interrupted!!");
}
});
readerThread.Start();
// wait for max 6 seconds
if (proc.WaitForExit(6_000))
{
// if command runs to an enc => wait for readerThread to collect error/output stream
readerThread.Join();
}
else
{
// if process takes longer than 6 seconds => kill reader thread and set error to timeout
readerThread.Interrupt();
error = "Timeout!";
}
// return output and error
return new Tuple<string, string>(output, error);
}
In my C# program I call an external program from command line using a process and redirecting the standard input. After I issue the command to the external program, every 3 seconds I have to issue another command to check the status - the program will respond with InProgress or Finished. I would like some help in doing this as efficient as possible. The process checks the status of a long running operation executed by a windows service (for reasons I would not like to detail I cannot interact directly with the service), therefore after each command the process exits, but the exitcode is always the same no matter the outcome.
use Process.Exited event and Process.ExitCode property
For examples:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx
You can use a Timer to execute some code at a specified interval, and Process.StandardOutput to read the output of the process:
Timer timer = new Timer(_ =>
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "foobar.exe";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
switch (output)
{
case "InProgress":
// ...
break;
case "Finished":
// ...
break;
}
});
timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(3));