Killing Java Process from C# Console App - c#

I posted about this a little while ago, but I resolved the other issue and ran into one more. I am about to deploy this program to 28 hosting machines so I want to make sure this is working before I do so.
I wrote a little c# NET application that is basically a wrapper for a Java application, when my app starts, the Java app starts, when my app closes, it closes, and so on.
Everything works properly except that when I close my application, the Java application continues to run. When I create the process, I store the Process var in a variable outside of the methods, and then use that when my application goes to shutdown. For whatever reason though it is not terminating the Java application.
class Program
{
private static Process minecraftProcess;
public static void LaunchMinecraft(String file, String memoryValue)
{
String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M ";
String args = memParams + "-jar " + file + " nogui";
ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
try
{
//using (Process minecraftProcess = Process.Start(processInfo))
using (minecraftProcess = Process.Start(processInfo))
{
minecraftProcess.WaitForExit();
}
}
catch
{
// Log Error
}
}
static void Main(string[] args)
{
Arguments CommandLine = new Arguments(args);
// Hook ProcessExit Event
AppDomain.CurrentDomain.ProcessExit += new EventHandler(Current_ProcessExit);
if (CommandLine["file"] != null && CommandLine["memory"] != null)
{
// Launch the Application (Command Line Parameters)
LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
}
else
{
// Launch the Application (Default Parameters)
LaunchMinecraft("minecraft_server.jar", "1024");
}
}
static void Current_ProcessExit(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(10000);
// If we have an active Minecraft Service, Shut it down
if (minecraftProcess != null)
{
minecraftProcess.Kill();
}
}
}

You can't Sleep in a ProcessExit handler.
The documentation states:
The total execution time of all
ProcessExit event handlers is limited,
just as the total execution time of
all finalizers is limited at process
shutdown. The default is two seconds.
An unmanaged host can change this
execution time by calling the
ICLRPolicyManager::SetTimeout method
with the OPR_ProcessExit enumeration
value.

Nevermind, I just realized the minecraftProcess variable is static.

Don't know if you did not solve this issue by yourself but:
You should be aware that there are Start methods for instances (returning bool) and static (returning a object).
You should not use using with something other than using-local variables!
Just this should work fine:
minecraftProcess = Process.Start(processInfo)
minecraftProcess.WaitForExit();

Related

WPF programme not running correctly when run silently

I have written a small programme to perform a quick configuration on a client machine and it needs to be able to run with a GUI and silently from the command line. If I run it with the GUI then it works perfectly, if however I try to run it without then it just hangs.
I have traced the problem to this section of code:
string arg = "/C:\"setup.exe /qn ADD_OPINSIGHTS_WORKSPACE=1 OPINSIGHTS_WORKSPACE_ID=" + workSpaceID + " OPINSIGHTS_WORKSPACE_KEY=" + workSpaceKey + " AcceptEndUserLicenseAgreement=1\"";
log.Info(arg);
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "MMASetup-AMD64.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = arg;
try
{
log.Info("try entered");
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
log.Info("Install started");
exeProcess.WaitForExit(30000);
log.Info("Install exit code: " + (exeProcess.ExitCode).ToString());
return (exeProcess.ExitCode).ToString();
}
}
catch (Exception e)
{
log.Error("MMA install threw an error: ", e);
return e.Message;
}
This method is in a seperate class to the GUI and silent code and is run in exactly the same way yet only reaches "Install started" when run silently. I know that the exe does finish so I have tried using the code in this solution but had the same problem:
ProcessStartInfo hanging on "WaitForExit"? Why?
I had the same Problem.
I made a startup class:
public partial class Startup {
// WPF App
private App _app;
[STAThread]
public static void Main(string[] args) {
try {
//Do what you need
//Check the args
//Start your setup silent
//start the WPF App if need it
this._app = new App();
this._app.InitializeComponent();
this._app.Run();
} catch (Exception ex) {
//Logging ex
}
}
After that you must change your Application Startup Object to the Startup Class.
I was running all of my work asynchronously and because I was not loading the GUI thread Windows was treating the application like a console app. Whereas a GUI thread would call other asynchronous methods and wait for them to finish a console application calls the methods and then closes because it has nothing left to do. The solution was to explicitly make the main thread wait like this:
public static void Main(string[] args)
{
try
{
Install().Wait();
}
catch (Exception ex)
{
}
}
private static async Task Install()
{}

Process.GetProcessesByName in BackgroundWorker

I'm having an issue related the the BackgroundWorker object and don't have enough experience in C# to understand what's going on. The program is an off-site patching utility. It works but I the UI isn't updating correctly because the processing and UI loop are in the same thread, so I'm looking at moving the processing into a BackgroundWorker.
Since executables are being patched, the patching process checks to make sure they aren't running before files are copied. The problem I'm seeing is with Process.GetProcessesByName. If I run Process.GetProcessesByName in bg_InstallPatch it appears to work fine, if I call it from within the handleLocalRunningProcesses method the "Couldn't get process information from performance counter." exception is thrown, and I can't find any documentation on why that is. Does something similar to running Invoke on a Form need to happen when calling the method?
The highest .NET runtime level I have available is 3.5.
private void handleLocalRunningProcesses(bool killIfFound = true)
{
logger.Debug("Looking up local processes");
String[] filesToUpload = files.Split(',');
foreach (String file in filesToUpload)
{
String[] fileName = file.Split('.');
logger.Debug("Checking " + fileName[0]);
/******** V Exception Throw Here V ********/
foreach (Process proc in Process.GetProcessesByName(fileName[0]))
try
{
int pid = proc.Id;
logger.Info("Process " + pid + " found running for " + file);
if (killIfFound)
try
{
logger.Info("Attempting to kill process " + pid);
proc.Kill();
if (!proc.WaitForExit(TIMEOUT_KILL_IN_MILLIS))
throw new ApplicationException(String.Format(ERROR_PROCESS_RUNNING, pid, "localhost"));
else
logger.Info("Process has been terminated.");
}
catch (Exception e)
{
logger.Error(e.Message, e);
throw new ApplicationException(String.Format(ERROR_PROCESS_RUNNING, pid, "localhost"));
}
}
finally
{
proc.Dispose();
}
}
logger.Debug("Finished looking up local processes");
}
public void bg_InstallPatch(Object sender, DoWorkEventArgs ea)
{
try
{
//..... Other Code .....
if (updateLocal)
{
logger.Info("Starting Local Updates");
/***Testing***/
logger.Debug("2Looking up local processes");
String[] filesToUpload = files.Split(',');
foreach (String file in filesToUpload)
{
String[] fileName = file.Split('.');
logger.Debug("2Checking " + fileName[0]);
/****** This works fine ******/
foreach (Process proc in Process.GetProcessesByName(fileName[0]))
try
{
int pid = proc.Id;
logger.Info("2Process " + pid + " found running for " + file);
}
finally
{
proc.Dispose();
}
}
/******/
handleLocalRunningProcesses(true);
//..... More Code .....
}
//..... More Code .....
}catch (Exception e)
{
logger.Error("Error installing patch", e);
throw e;
}
}
public void installPatch()
{
//..... Unrelated Code ....
logger.Info("Starting patch installation");
BackgroundWorker patcher = new BackgroundWorker();
patcher.DoWork += new DoWorkEventHandler(bg_InstallPatch);
patcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_ProgressClose);
patcher.RunWorkerAsync(bar);
//..... More Code .....
}
I don't know the why, but I found the cause. The program showing this behavior is required to run on Windows XP under .NET 3.5. The issue no longer presented itself when running on Windows 10 with .NET 4.5.1 installed. A second test on Windows 8.0 with .NET 3.5 installed also worked. Verified that the program continues to fail in a second, unrelated XP environment with .NET 3.5 installed. The same executable was used for all tests.
Even though the program is compiled as a 32-bit executable, it should still be pointed out that XP is 32-bit and both Windows 8 and 10 were 64-bit. Just in case this behavior would present itself in the 32-bit version of newer operating systems, though I doubt it would.

Redirecting standard output

I have a C# application A which calls another C# application B, which calls multiple instances of application C.
I would like to redirect the output of application C to the output of application A.
I already have a working redirection of the output of application B into the output of application A.
Now, from within application B's code, I'm redirecting every process's output, and I'm printing the redirected output to the console. Unfortunately, for some reason, nothing is printed.
(I'm currently testing it without using application A - I'm only running application B).
Here is the code:
private void runSingleFile (string execFile, string commandArgs)
{
Process processToRun = new Process();
processToRun .StartInfo.FileName = execFile;
processToRun .StartInfo.Arguments = commandArgs;
processToRun .StartInfo.UseShellExecute = false;
processToRun .StartInfo.RedirectStandardOutput = true;
processToRun .OutputDataReceived += outputRedirection;
processToRun.Start();
Console.WriteLine("");
Thread.Sleep(100);
processToRun.BeginOutputReadLine();
}
private void outputRedirection(object sendingProcess, DataReceivedEventArgs outLine)
{
try
{
if (outLine.Data != null)
Console.WriteLine(outLine.Data);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
Any ideas?
The .net Process object doesn't make it easy for one to "do the right thing" with respect to correctly handling the IO.
These pages list some of the concerns that need to be dealt with:
MSDN's ProcessStartInfo.RedirectStandardOutput Property page
Raymond's blog Be careful when redirecting both a process's stdin and stdout to pipes...
C# test.net's How to use System.Diagnostics.Process correctly
From your code sample, here are some of the items that you will want to look at:
You will want to capture both stderr and stdin (the latter should be immediately closed if not used).
You also need to be aware that you can still receive events on your outputRedirection callback after the child process has exited.
The code you have posted works. Given test program
// ConsoleApplication2.exe
static void Main(string[] args)
{
Console.WriteLine("Test1...");
Console.WriteLine("Test2...");
System.Threading.Thread.Sleep(100);
Console.WriteLine("Test3...");
}
called as :
static void Main(string[] args)
{
runSingleFile("ConsoleApplication2.exe", "");
runSingleFile("ConsoleApplication2.exe", "");
runSingleFile("ConsoleApplication2.exe", "");
Console.ReadLine();
}
produces output :
Clearly something else is not working in another part of your code (Something you have not shown us).
The most likely explanation, if application C is working correctly, is that application B is terminating before all instances of C have completed. You may have to add some code that makes B wait for all instances of C to return.
Note that :
static void Main(string[] args)
{
runSingleFile("ConsoleApplication2.exe", "");
runSingleFile("ConsoleApplication2.exe", "");
runSingleFile("ConsoleApplication2.exe", "");
//Console.ReadLine(); // ** Don't wait!
}
completes immediately and fails to return some or all of the data (especially if you remove the Sleep call in runSingleFile.
Consider :
static long processCount = 0; //ADD
static void runSingleFile(string execFile, string commandArgs)
{
Interlocked.Increment(ref processCount); //ADD
Process processToRun = new Process();
processToRun.StartInfo.FileName = execFile;
processToRun.StartInfo.Arguments = commandArgs;
processToRun.StartInfo.UseShellExecute = false;
processToRun.StartInfo.RedirectStandardOutput = true;
processToRun.OutputDataReceived += outputRedirection;
processToRun.EnableRaisingEvents = true; //ADD
processToRun.Exited += processExited; //ADD
processToRun.Start();
Console.WriteLine("");
processToRun.BeginOutputReadLine();
}
static void processExited(object sender, EventArgs e)
{
Interlocked.Decrement(ref processCount);
}
with
static void Main(string[] args)
{
runSingleFile("ConsoleApplication2.exe", "");
runSingleFile("ConsoleApplication2.exe", "");
runSingleFile("ConsoleApplication2.exe", "");
while (Interlocked.Read(ref processCount) > 0)
{
System.Threading.Thread.Sleep(100);
}
}
The above then makes application B wait until all spawned processes have returned. The example is simplistic and obviously can be improved upon, but it demonstrates the problem, I think, and offers a method for the solution.
You might be tempted to use something more elegant like WaitHandle.WaitAll(), but this does introduce the problem that josh noted where your output events may not fire until after the process terminates - the process handle will signal that it has terminated but its posted messages may still be in the queue. Waiting on the Exited event tidies up that race condition since that event will always be the last message in the queue (AFAIK).
Also, note the use of Interlocked functions here - Console.WriteLine is threadsafe but other variable access is not. Since there is no synchronization context in a console application the events raised by spawned processes are handled by threads in the threadpool (not the main thread of the console application). This introduces all of the issues associated with multithreading which must be managed appropriately.

Restart an application by itself

I want to build my application with the function to restart itself. I found on codeproject
ProcessStartInfo Info=new ProcessStartInfo();
Info.Arguments="/C choice /C Y /N /D Y /T 3 & Del "+
Application.ExecutablePath;
Info.WindowStyle=ProcessWindowStyle.Hidden;
Info.CreateNoWindow=true;
Info.FileName="cmd.exe";
Process.Start(Info);
Application.Exit();
This does not work at all...
And the other problem is, how to start it again like this?
Maybe there are also arguments to start applications.
Edit:
http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=31454&av=58703
I use similar code to the code you tried when restarting apps. I send a timed cmd command to restart the app for me like this:
ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
Application.Exit();
The command is sent to the OS, the ping pauses the script for 2-3 seconds, by which time the application has exited from Application.Exit(), then the next command after the ping starts it again.
Note: The \" puts quotes around the path, incase it has spaces, which cmd can't process without quotes.
Hope this helps!
Why not use
Application.Restart();
??
More on Restart
Why not just the following?
Process.Start(Application.ExecutablePath);
Application.Exit();
If you want to be sure the app does not run twice either use Environment.Exit(-1) which kills the process instantaneously (not really the nice way) or something like starting a second app, which checks for the process of the main app and starts it again as soon as the process is gone.
You have the initial application A, you want to restart.
So, When you want to kill A, a little application B is started, B kill A, then B start A, and kill B.
To start a process:
Process.Start("A.exe");
To kill a process, is something like this
Process[] procs = Process.GetProcessesByName("B");
foreach (Process proc in procs)
proc.Kill();
A lot of people are suggesting to use Application.Restart. In reality, this function rarely performs as expected. I have never had it shut down the application I am calling it from. I have always had to close the application through other methods such as closing the main form.
You have two ways of handling this. You either have an external program that closes the calling process and starts a new one,
or,
you have the start of your new software kill other instances of same application if an argument is passed as restart.
private void Application_Startup(object sender, StartupEventArgs e)
{
try
{
if (e.Args.Length > 0)
{
foreach (string arg in e.Args)
{
if (arg == "-restart")
{
// WaitForConnection.exe
foreach (Process p in Process.GetProcesses())
{
// In case we get Access Denied
try
{
if (p.MainModule.FileName.ToLower().EndsWith("yourapp.exe"))
{
p.Kill();
p.WaitForExit();
break;
}
}
catch
{ }
}
}
}
}
}
catch
{
}
}
Winforms has the Application.Restart() method, which does just that. If you're using WPF, you can simply add a reference to System.Windows.Forms and call it.
Another way of doing this which feels a little cleaner than these solutions is to run a batch file which includes a specific delay to wait for the current application to terminate. This has the added benefit of preventing the two application instances from being open at the same time.
Example windows batch file ("restart.bat"):
sleep 5
start "" "C:\Dev\MyApplication.exe"
In the application, add this code:
// Launch the restart batch file
Process.Start(#"C:\Dev\restart.bat");
// Close the current application (for WPF case)
Application.Current.MainWindow.Close();
// Close the current application (for WinForms case)
Application.Exit();
My solution:
private static bool _exiting;
private static readonly object SynchObj = new object();
public static void ApplicationRestart(params string[] commandLine)
{
lock (SynchObj)
{
if (Assembly.GetEntryAssembly() == null)
{
throw new NotSupportedException("RestartNotSupported");
}
if (_exiting)
{
return;
}
_exiting = true;
if (Environment.OSVersion.Version.Major < 6)
{
return;
}
bool cancelExit = true;
try
{
List<Form> openForms = Application.OpenForms.OfType<Form>().ToList();
for (int i = openForms.Count - 1; i >= 0; i--)
{
Form f = openForms[i];
if (f.InvokeRequired)
{
f.Invoke(new MethodInvoker(() =>
{
f.FormClosing += (sender, args) => cancelExit = args.Cancel;
f.Close();
}));
}
else
{
f.FormClosing += (sender, args) => cancelExit = args.Cancel;
f.Close();
}
if (cancelExit) break;
}
if (cancelExit) return;
Process.Start(new ProcessStartInfo
{
UseShellExecute = true,
WorkingDirectory = Environment.CurrentDirectory,
FileName = Application.ExecutablePath,
Arguments = commandLine.Length > 0 ? string.Join(" ", commandLine) : string.Empty
});
Application.Exit();
}
finally
{
_exiting = false;
}
}
}
This worked for me:
Process.Start(Process.GetCurrentProcess().MainModule.FileName);
Application.Current.Shutdown();
Some of the other answers have neat things like waiting for a ping to give the initial application time to wind down, but if you just need something simple, this is nice.
For .Net application solution looks like this:
System.Web.HttpRuntime.UnloadAppDomain()
I used this to restart my web application after changing AppSettings in myconfig file.
System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
configuration.AppSettings.Settings["SiteMode"].Value = model.SiteMode.ToString();
configuration.Save();

How to pass arguments to a console application if it is already running?

I use a Console Application in Windows Mobile to handle incoming message interception. In the same console application i accept parameters (string args[]) which based on the parameters, register the message interceptor.
InterceptorType is a enum
static void Main(string[] args)
{
if (args[0] == "Location")
{
addInterception(InterceptorType.Location, args[1],args[2]);
}
}
private static void addInterception(InterceptorType type, string Location, string Number )
{
if (type == InterceptorType.Location)
{
using (MessageInterceptor interceptor = new MessageInterceptor(InterceptionAction.NotifyAndDelete, false))
{
interceptor.MessageCondition = new MessageCondition(MessageProperty.Sender, MessagePropertyComparisonType.Contains, Number, false);
string myAppPath = Assembly.GetExecutingAssembly().GetName().CodeBase;
interceptor.EnableApplicationLauncher("Location", myAppPath);
interceptor.MessageReceived += new MessageInterceptorEventHandler(interceptor_MessageReceived);
}
}
}
static void interceptor_MessageReceived(object sender, MessageInterceptorEventArgs e)
{
//Do something
}
I made this a console application because i want it keep running in the background and intercept incoming messages.
This works fine for the first time. But the problem is that I have to keep calling the addInterception method to add subsequent interception rules. This makes the console application start again and again for each time i add a rule. How do i make this run only once and add more message interceptor rules?
Since you already have a method in place to call the command prompt once, update your logic with some simple looping so you can pass N commands.
EDIT: I wrote it a fully compileable example to show you exactly what I am talking about. Note how the child process can be called any number of times without re-launching. This is not just a simple command line launch with arguments being passed because that idea will lead to X processes which is exactly what you do not want.
PARENT PROCESS: (The one with System.Diagnostics.Process)
/// <summary>
/// This is the calling application. The one where u currently have System.Diagnostics.Process
/// </summary>
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process p = new Process();
p.StartInfo.CreateNoWindow = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = #"C:\AppfolderThing\ConsoleApplication1.exe";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output received from application: {0}", e.Data);
};
p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output received from application: {0}", e.Data);
};
p.BeginErrorReadLine();
p.BeginOutputReadLine();
StreamWriter inputStream = p.StandardInput;
inputStream.WriteLine(1);
inputStream.WriteLine(2);
inputStream.WriteLine(-1);//tell it to exit
p.WaitForExit();
}
}
CHILD PROCESS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
enum InterceptorType
{
foo,
bar,
zee,
brah
}
/// <summary>
/// This is the child process called by System.Diagnostics.Process
/// </summary>
class Program
{
public static void Main()
{
while (true)
{
int command = int.Parse(Console.ReadLine());
if (command == -1)
Environment.Exit(0);
else
addInterception((InterceptorType)command, "some location", "0");
}
}
private static void addInterception(InterceptorType type, string Location, string Number)
{
switch (type)
{
case InterceptorType.foo: Console.WriteLine("bind foo"); break;
case InterceptorType.bar: Console.WriteLine("bind bar"); break;
default: Console.WriteLine("default bind zee"); break;
}
}
static void interceptor_MessageReceived(object sender, EventArgs e)
{
//Do something
}
}
}
Note that codeplex has a managed service library.
EDIT
It seems that people are misunterstanding your question (or I am) so here's some clarification on how I'm seeing the problem.
You have an console app that takes in command-line parameters. These parameters are used for something (the what is irrelevant actually). You want to be able to add parameters after the app is already running by calling the app with new command line args.
What is happening is that when you call the app any time after teh first, a new instance of the process starts up instead of the command-line arguments going to the existing, already running application.
END EDIT
The solution is fairly straightforward and requires two pieces.
You need a named mutex. For whatever (poor) reason, the CF doesn't expose a version of a mutex that takes a name, so you have to P/Invoke CreateMutex or use a library (like the SDF) that already has it. Your app needs to create the mutex at startup and check to see if it already exists. if it doesn't you're the first running instance and run as normal. If the mutex exists, you need to pass your command line args to the one that is already running via a P2P queue then simply exits.
After checking the mutex, the first instance spawns a worker thread. This thread listens on a P2P queue for messages. When they come in, you handle them.

Categories