Kill a specific event handle of a running process? - c#

I am trying to close a specific singleton handle associated with a process. The windows application "Process Explorer" allows you to do this but you need to select the process, then right click on the handle and select close. I am after a solution that will allow me to auto close the specific handle when the application is running.
I know I can get all processes and even kill a process by simply doing:
foreach (var p in Process.GetProcessesByName("your.exe"))
{
p.Kill();
}
But how would I go about closing a handle attached the process and not the process itself?

I ended up using NtDuplicateObject as Michael suggested in the comments. It was a bit of a pain to implement but everything works as expected - thanks Michael!

Related

Capture .Net Console Kill or Terminate

So I have a hidden console application called Hidden.exe running.
Another application Call Killer.exe will find the process Hidden.exe or its PID, and Kills the process.
How do i programmatically capture a kill command or a terminate from Task Manager? A user can browse through the process list and 'End Task' on Hidden.exe and I want to be able to capture this event and do some cleanup before it exits.
How can i do this? I have searched around, and explored alternatives from
.NET console application exit event
Send WM_CLOSE message to a process with no window
Can I send a ctrl-C (SIGINT) to an application on Windows?
etc....
But they all dont work or only work in some cases, my case is for a hidden console application and needs to somehow capture a Kill on it. None of the above solution seem to have a 'correct' solution.
There is no such answer. A kill will always work and will fire no event. This is due to security concern to prevent virus and/or malware code.
I've since found another way.

Right way to run, kill and keep process running

In my application, which using another application (run in tray) to print receipts I need to do those three things:
Open process when on mainApplication startup
Close process when mainApplication closing or changing any information about printer
Keep process alive, if it get any error
First point is quiet easy, I just simply
Process.Start("_ReceiptPrinter.exe");
And process working ;)
But now, the two other issues:
Closing process. I've tried this code:
Process[] allProcs = Process.GetProcesses();
foreach (Process proc in allProcs)
{
ProcessThreadCollection myThreads = proc.Threads;
if (proc.ProcessName == "_ReceiptPrinter")
{
proc.Close();
}
}
Unfortunately, I can still see icon in tray, and process is still running.
Keep process alive. My main application is in WPF, that one from tray is written on WinForms. Maybe there is any way to handle ANY WinForm application exit event (well, any, but not this one, which just simply close it from another application), and reopen it?
proc.Close() asks it to close but there is no guarantee. Use:
proc.Kill();
The reason you still see a tray icon is that the icons are cached by an external process (windows explorer.)
The reason process.Close() does not close the application is because the application is not processing window messages (as this call simulates a WM_CLOSE request, per classic Windows API.)
The proper way to close the application is process.Close, not process.Kill(), further, as part of app/window close you need to unregister any tray icons you've registered with the system. This way any normal closure of your application will properly clean-up the tray.
Further, you can use a "critical finalizer" which would be guaranteed to run before application exit, except in total catastrophe scenarios.

C# - Terminate another proccess when mine still running

i was wrote some codes, when my apps still run, it will close another (example notepad) even the notepad is reopen it will close again, i've try some, but it will close when my apps startup , when my apps is running, and i open notepad, notepad wont close. here
foreach (Process Proc in Process.GetProcesses())
if (Proc.ProcessName.Equals("notepad"))
Proc.Kill();
Your code kills processes that are running at the time you code executes. Once your code has finished executing it no longer exerts any influence. It won't kill processes that are started after your code has finished executing.
Probably you need to detect when the target process starts, and then kill it. You can do that by polling which is rather inelegant. To avoid polling you need WMI. There are many examples of how to do this. For instance: How to detect a process start & end using c# in windows?

Alternative methods to kill a running process in C#

I am having a bit of trouble trying to terminate a process, I realize there is a fair amount of recourses on this site alone, but I was wondering if there's any alternative ways of terminating an application rather than something typical such as:
Process[] procs = Process.GetProcessesByName("test");
foreach (Process proc in procs)
proc.Kill();
There's Process.CloseMainWindow, which nicely asks the process to quit (as opposed to Process.Kill, which shoots down the process and can have negative side effects).
There are only 2 ways in C# to close the Process (AFAIK) using Process.Kill() and Process.CloseMainWindow(), Kill sends an immediate KILL signal to the application and forces it to close immediately. CloseMainWindow uses SendWindowMessage to send a CLOSE signal to the main application. Kill can be unsafe because it immediately stops the process. CloseMainWindow can be followed by Process.WaitForExit so that you can be sure that the application has closed and may continue to do work knowing that the process you told to exit has exited correctly. As posted by Heinzi's comment please be a little more specific I'm just trying to expand on what was said in the hopes that this is what you require.
Very simple, just need to get the process name and kill it, don't try to do anything fancy, sometimes less is more...
Process[] prs = Process.GetProcesses();
foreach (Process pr in prs)
{
if (pr.ProcessName == "test")
{
pr.Kill();
}
}
This idea is not good. There could be another running process(es) with that name. Do you want any process with that name to be terminated? Unless you are writing a Task Manager/Process Explorer kind of application, you should never do that. And even with TM kind of application, you close the process by grabbing its handle/Process object, and not by name.
Thy can't you ask the target process to close itself gracefully? May be you can use a named mutex, the target thread would wait on that mutex. When you signal that named-mutex from another process, the target thread would know it is time to exit and eventually exit.

C# Detecting Spawned Processes

I'm writing a piece of c# code that launches an installer and waits for it to return before continuing with other stuff.
I'm having trouble with certain installers that spawn other processes with the original process returning before the install has actual finished. Is there some way that I can wait until all the processes have finished?
To clarify here's the scenario I'm having trouble with:
Launch Installer1
Installer1 spawns/launches another installer (Installer2)
Installer 1 returns
Application thinks install has finished but Installer2 is still running. This causes issues with workflow in the app.
Here's the code I'm using at the moment:
// launch installer
Process process = windowsApplicationLauncher.LaunchApplication(_localFilePath);
// wait for process to return
do
{
if (!process.HasExited)
{
}
}
while (!process.WaitForExit(1000));
if (process.ExitCode == 0)
{
_fileService.MoveFile(_localFilePath, _postInstallFilePath);
_notification.SetComplete(false);
return true;
}
return false;
Have you thought about using WMI to solve this problem?
You can use WMI to listen for process creation and deletion events. Question 967668 has a good example.
When you receive a process creation event, you could issue a WMI query to determine if the process is a child (or a child of a child etc) of your root installer with something like the following:
"SELECT * FROM Win32_Process WHERE ParentProcessId=".
It might be better to do it this way inside the do / while loop:
System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(proc.ProcessName, Environment.MachineName);
Then iterate through the procs to find out which is still running...by using the HasExited property...
The logic being that the process's subprocesses are owned by your code, so you could check first if they have exited or not, if not, keep looping...
Hope this helps,
Best regards,
Tom.

Categories

Resources