How to do: The first instance of an app will execute a process, second instance will kill the process later
I want to create a console application that behaves as follows:
- The first instance of the app will execute a process.
- The second instance executed later will kill the process.
Is there a simple way to do so?
EDIT: The second instance also terminates the first instance and itself.
EDIT 2:
More details scenario is as follows:
Assume there is no instance of my application running. If I execute my application, the new instance will run. The application will create a process that execute Adobe Acrobat Reader X (for example).
Later, I execute my application again just to kill the running Adobe Acrobat Reader X and of course its host (the first instance of my开发者_运维百科 application).
You need to implement a mutex to do this.
private static Mutex mutex = null;
private void CheckIfRunning() {
string strId = "291B62B2-812A-4a13-A657-BA672DD0C93B";
bool bCreated;
try
{
mutex = new Mutex(false, strId, out bCreated);
}
catch (Exception)
{
bCreated = false;
//Todo: Kill your process
}
if (!bCreated)
{
MessageBox.Show(Resources.lbliLinkAlreadyOpen, Resources.lblError, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
You can create a process with a known name. Then when the application starts you could get a list with all the processes that are running. If the process is not there you can start it, if it's already there you can kill the process and exit.
A more elegant solution would be as Max suggested to use a Mutex to communicate between the processes. For example to be sure that you don't kill another process with the same name.
精彩评论