Hint
Hint

Reputation: 130

Closing a running program from commandline

Visual Studio 2010 C#

Is it possible to run and close a program from commandline? I need to do something like that:

myProgram.exe -start
-- do something --
myProgram.exe -stop

I know how to implement the first part (String[] args in main) but how can I close my running program?


Edit

myProgram.exe is handling some UDP communication and have to be executed while the stuff in -- do something -- is executed. Sorry for beeing imprecise.

Upvotes: 1

Views: 2177

Answers (5)

Oliver
Oliver

Reputation: 45109

As Fox32 already mentioned in his comment you should really take this approach, cause in that case your application can really shutdown itself gracefully. If you simply go and use taskkill, etc to kill your process from the outer world you could really get into trouble depending of resources you are using (network, database, files, etc.).

Upvotes: 0

Mike Miller
Mike Miller

Reputation: 16575

I'm guessing you know how to inspect the command line arguments and find if stop has been specified? The following should do the job.

        var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
        var matchingProcesses = System.Diagnostics.Process.GetProcesses().Where(x => x.Id != currentProcess.Id && x.ProcessName == currentProcess.ProcessName);
        foreach (var process in matchingProcesses) {
            process.Kill();
        }

Upvotes: 1

hungryMind
hungryMind

Reputation: 7009

  • Get Process Id by name
  • Kill the process

Upvotes: 0

Shai
Shai

Reputation: 25595

Is it possible to use taskkill for things like that.

i.e if you want to close myProgram.exe, you can execute

taskkill /IM myProgram.exe

Upvotes: 1

Oded
Oded

Reputation: 499382

Use a command line program that is designed to shut down processes - pskill is one such program.

pskill myProgram.exe

A built in utility is taskkill:

taskkill /im myProgram.exe

Upvotes: 0

Related Questions