简体   繁体   中英

Determine thread which holds the lock on file

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.

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.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM