How to run console application from Windows Service?
I've done this before successfully - I have some code at home. When I get home tonight, I'll update this answer with the working code of a service launching a console app.
I thought I'd try this from scratch. Here's some code I wrote that launches a console app. I installed it as a service and ran it and it worked properly: cmd.exe launches (as seen in Task Manager) and lives for 10 seconds until I send it the exit command. I hope this helps your situation as it does work properly as expected here.
using (System.Diagnostics.Process process = new System.Diagnostics.Process())
{
process.StartInfo = new System.Diagnostics.ProcessStartInfo(@"c:\windows\system32\cmd.exe");
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.Start();
//// do some other things while you wait...
System.Threading.Thread.Sleep(10000); // simulate doing other things...
process.StandardInput.WriteLine("exit"); // tell console to exit
if (!process.HasExited)
{
process.WaitForExit(120000); // give 2 minutes for process to finish
if (!process.HasExited)
{
process.Kill(); // took too long, kill it off
}
}
}
Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.
On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.
If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.
ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(info);
See if this does the trick.
First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).
Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput
and process.StandardOutput
.
Windows Services do not have UIs. You can redirect the output from a console app to your service with the code shown in this question.