4

I'm writing a temporary file manager for other developers. I want to remove files even our console applications crashes or being closed by "X" button.

So far I found std::set_terminate, std::atexit and SetConsoleCtrlHandler methods with which I can delete all temporary files I need. Problem is - I can't delete opened files. Furthermore - I cant control streams to those files, cause developers using several libraries (GDAL for example) which uses their own stream mechanisms and can accept only a target file path.

How can I force close and delete all files, opened by current application?

Vasilly.Prokopyev
  • 856
  • 1
  • 10
  • 24
  • 5
    Write a launcher application that does all the cleaning up. The launcher calls `CreateProcess` and `WaitForSingleObject` on the process handle. The process handle is signaled, regardless of how the process terminates (clean shutdown, crash, etc.). You don't have to worry about *force closing* files either - the OS closes all handles held by a process upon process termination. – IInspectable Aug 21 '14 at 14:12
  • Can it be done without complications with IPC? – Vasilly.Prokopyev Aug 21 '14 at 15:56
  • What sort of complications with IPC? There is no IPC involved. You launch the target process and wait for termination. Once the target process terminated, you can go ahead and perform necessary cleanup. And that's really all there is to it. – IInspectable Aug 21 '14 at 16:23
  • I dont know which files to clean. There is more than one instances of app. But now I see that It can be solved with some kind of naming convention – Vasilly.Prokopyev Aug 21 '14 at 16:27
  • After all I decided to use @IInspectable solution. But rather make it as service nor the starter app, using some info from [`this question`](http://stackoverflow.com/questions/3556048/how-to-detect-win32-process-creation-termination-in-c) Pleace post it as answer so I could mark it. Or may I post it myself? – Vasilly.Prokopyev Aug 26 '14 at 09:55
  • Open your temporary files with `FILE_FLAG_DELETE_ON_CLOSE`. When the handle is closed, the file will be deleted. If the process crashes, the kernel closes the handles, at which point the files will be deleted. – Raymond Chen Sep 03 '14 at 06:38
  • @RaymondChen, I use some libraries like GDAL, whish decides how to open files by theyself. – Vasilly.Prokopyev Sep 03 '14 at 06:40

2 Answers2

7

You need to close the file handles owned by your current process. To do this:

  • Use the NtQuerySystemInformation API with undocumented SystemHandleInformation parameter.
  • This gives you an array of all handles open in the system
  • Iterate over array and select only ones which match your process PID, and are file handles
  • You can then further narrow it down using GetFinalPathNameByHandle to get paths of opened files e.g. you could select specific file names or all files with tmp in their name.
  • For any files you want to delete, call CloseHandle() to force close the handle, then of course DeleteFile() on the path.

Some code (without any error checking):

SYSTEM_HANDLE_INFORMATION* pInfo=NULL;
DWORD dwSize=0;
NTSTATUS status=0;

do
{
  // keep reallocing until buffer is big enough
  status = NtQuerySystemInformation(SystemHandleInformation, pInfo, dwSize, &dwSize);
  if (status==STATUS_INFO_LENGTH_MISMATCH)
     pInfo = (SYSTEM_HANDLE_INFORMATION*)realloc(pInfo, dwSize);
} while(status!=0);

// iterate over every handle
for (DWORD i=0; i<pInfo->dwCount; i++)
{
  if (pInfo->handles[i].ProcessID==GetCurrentProcessId() && pInfo->handles[i].HandleType==28)
  {
     TCHAR szPath[MAX_PATH];
     GetFinalPathNameByHandle((HANDLE)pInfo->handles[i].HandleNumber, szPath, MAX_PATH, 0);
     if (_tcsstr(szFilePath, L"filename_I_want_to_delete"))
     {
       CloseHandle((HANDLE)pInfo->handles[i].HandleNumber);
       DeleteFile(szPath);
     }
  }
}

This is assuming all the files you need to delete are owned by the process doing the deletion. If any of the files belong to another process you will need an extra step using DuplicateHandle() with the DUPLICATE_CLOSE_SOURCE option. Assuming you have suitable permissions this gives you the handle, which you can then close and delete the file as before.

There is some good sample code here.

snowcrash09
  • 4,694
  • 27
  • 45
  • 1
    This will not work reliably, due to the [TOCTOU](http://en.wikipedia.org/wiki/Time_of_check_to_time_of_use) race. – IInspectable Aug 21 '14 at 16:27
  • @IInspectable - you could be right but can you elaborate - which part specifically do you think will be a problem? – snowcrash09 Aug 21 '14 at 16:34
  • 1
    The state can change in between capturing a snapshot (`NtQuerySystemInformation`) and using this information inside the loop. At the point you're evaluating `ProcessID`, the information may have changed already. Likewise, the result of the check for the filename may no longer represent the current state when calling `CloseHandle`. Handles do get reused, and you might be closing a handle to a completely different kernel object. – IInspectable Aug 23 '14 at 11:18
4

After all I decieded to use IInspectable's solution, which he posts in comments. Just posting it as answer, so I could mark it

Write a launcher application that does all the cleaning up. The launcher calls CreateProcess and WaitForSingleObject on the process handle. The process handle is signaled, regardless of how the process terminates (clean shutdown, crash, etc.). You don't have to worry about force closing files either - the OS closes all handles held by a process upon process termination.

Vasilly.Prokopyev
  • 856
  • 1
  • 10
  • 24