1

I know that Mutex can be used to determine if another instance of application is running, but can I find from Mutex the PID or name of the other instance? And if not from Mutex, is there another way around to kill other instance if it is running. This is kinda tricky, because it also must be bounded to user and it shouldn't use files to do the trick (I know that Mutex creates files, but those created by .NET via internal functions are OK).

Note that I need to get info of other instance to kill it.

Thanks for reading!

Cryo Erger
  • 61
  • 1
  • 8
  • 2
    Is this other process something you wrote? Or are you trying to kill some other process? – Ron Beyer Jun 09 '15 at 17:52
  • possible duplicate of [Checking if Windows Application is running](http://stackoverflow.com/questions/4722198/checking-if-windows-application-is-running) – t3dodson Jun 09 '15 at 17:53
  • Does the application have to start a second time or would it be sufficient if Windows detects the already started process and prevents the second startup ? – Marged Jun 09 '15 at 17:56
  • It is application that I wrote. And yes it has to start a second time – Cryo Erger Jun 09 '15 at 18:00
  • `Mutex` isn't probably going to be the best option, it will work but if you kill the process and it doesn't release the mutex, it'll never allow another instance to run and you'll have to clean up the mutex manually. See http://stackoverflow.com/questions/646480/is-using-a-mutex-to-prevent-multiple-instances-of-the-same-program-from-running The better way may be to just examine the list of running processes and kill the duplicate through a command line using the `Process` class with the `Taskkill /IM whatever.exe /F` command – Ron Beyer Jun 09 '15 at 18:04
  • Isn't there a way to kill the other process even if it has more file names (eg.: A.exe, B.exe are the same but started under different names)? – Cryo Erger Jun 09 '15 at 18:07

1 Answers1

1

Something like this ought to do you:

static void Main(string[] args)
{
  HashSet<string> targets = new HashSet<string>( args.Select( a => new FileInfo(a).FullName ) , StringComparer.OrdinalIgnoreCase ) ;

  foreach ( Process p in Process.GetProcesses().Where( p => targets.Contains(p.MainModule.FileName) ) )
  {
    Console.WriteLine( "Killing process id '{0}' (pid={1}), main module: {2}" ,
      p.ProcessName ,
      p.Id ,
      p.MainModule.FileName
      ) ;
    try
    {
      p.Kill() ;
      Console.WriteLine("...Killed");
    }
    catch ( Exception e )
    {
      Console.WriteLine( "...well, that was unexpected. Error: {1}" , e.Message ) ;
    }
  }
  return;
}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135