0
votes

I know there is no WINAPI which would do it, but if a thread is hung and holds an open handle of file. how do we determine the thread id and Terminate it within our processes.

I'm not talking about releasing file locks in other processes but within my own process.

it could also be possible that thread has crashed / terminated without closing the handle.

4
Does the thread block during file processing in certain circumstances or every time? - ChadNC
well its under certain circumstances, but in separate area I've to delete that file, but it gets access denied error since i know its my own process, if I can figure out the thread, I can terminate it or close handle or even figure out for debugging which thread and why.. - AppDeveloper
You should never call TerminateThread, see stackoverflow.com/questions/1004676/…. - Michael
it depends. for example if you used mutexes the ownership transfers. although i agree its not generally safe but I don't think never is the right statement. - AppDeveloper
@SnapConfig - you can only safely kill a thread if you can guarantee it is executing in code you control and that its termination will have no side-effects. If it is inside any code provided by a library or the OS, you cannot reliably terminate it. The only clear safe case is if the thread is created suspended and hasn't started running yet. - Michael

4 Answers

0
votes

You could attach to the process with the debugger when this happens, pause the program, search for the thread that caused this, and, traversing the stack, find out what it's doing, which code it executes, and which variables are on the stack.

If you used RAII for locking, this should be enough, as the lock must be on the stack.

0
votes

I haven't seen anything browsing MSDN, although there's certainly something perhaps undocumented out there that can give you the information you need.

If your threads are creating these resources, and there's an expectation that one of these threads might go out to lunch, would it make more sense for them to query resources from a utility thread who's sole job is to create and dispose of resources? Such a thread would be unlikely to crash, and you would always know, in case of a crash, that the resource thread is in fact the owner of these handles.

0
votes

You cannot determine which thread holds an open handle to a file. Nearly all kernel handles, including file handles, are not associated with a thread but only with a process (mutexes are an exception - they have a concept of an owning thread.)

Suppose I have the following code. Which thread "owns" the file handle?

void FuncCalledOnThread1()
{
     HANDLE file = CreateFile(...);

     // Hand off to a background thread.
     PostWorkItemToOtherThread(FuncCalledOnThread2, file);
}

void FuncCalledOnThread2(HANDLE file)
{
       DoSomethingWithFile(file);
       CloseHandle(file);
}