views:

259

answers:

4

Hi,

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.

A: 

Use Process Explorer - http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx [edit, or Handle - http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx ]

andrew cooke
I think he wants to do it programmatically.
Doug T.
Ah, ok. No idea then, sorry.
andrew cooke
A: 

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.

sbi
I can't its on customer machine where they would not let us debug it. :(..aaaah RAII its 1.5 mil lines of code written over 10 years :).. I"m just fixing it..
AppDeveloper
You're a hero. I once worked in a several MLoC C++ project which, in its kernel, was ten years old, too. But that was decent C++ even in the oldest parts (and good in newer ones). Anyway, the only ways I have found out of MT bugs are logging, logging, and logging.
sbi
A: 

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.

Doug T.
A: 

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);
}
Michael
Good point. though i did find some source for enumerating handles just for someone else's reference.http://forum.sysinternals.com/forum_posts.asp?TID=18892
AppDeveloper