简体   繁体   English

如何释放流程的所有资源?

[英]How to release all resources for a process?

I am running a process, which is creating a file and using that file. 我正在运行一个进程,该进程正在创建文件并使用该文件。 After the end of that process, i am deleting that file. 该过程结束后,我正在删除该文件。

If some exception arises in between then how to know that the file is released by the process or not and how to delete it if it is locked by the process. 如果在这之间发生异常,那么如何知道文件是否由进程释放,以及如果文件被进程锁定则如何删除。

Thanks for any help :) 谢谢你的帮助 :)

On Windows, when the process ends, the OS returns all resources owned by that process automatically. 在Windows上,当进程结束时,操作系统会自动返回该进程拥有的所有资源。 End of story. 故事结局。

For example, say you did "CreateFileMapping()" on each of two processes to share a memory segment. 例如,假设您在两个进程中的每个进程上执行了“ CreateFileMapping()”以共享一个内存段。 When the first process exits, Windows decrements the usage counter, and only the surviving process can still use the object. 当第一个进程退出时,Windows递减使用计数器,只有尚存的进程仍可以使用该对象。 When the second process does a "CloseHandle()" (or itself exits), the counter is decremented to zero, and the object is completely freed. 当第二个进程执行“ CloseHandle()”(或自身退出)时,计数器递减为零,并且对象完全释放。

In other words, Windows will reclaim the resource when it's no longer used, whether the processes clean up gracefully after themselves or not. 换句话说,Windows将在不再使用该资源时回收该资源,而无论进程是否在其自身之后正常清理。

And no, even if you open a file for exclusive access, the file itself won't be "locked" once the file handle is closed (and Windows WILL close it automatically when the program terminates). 而且不会,即使您打开文件以进行独占访问,一旦关闭文件句柄,文件本身也不会被“锁定”(并且Windows会在程序终止时自动将其关闭)。

When your program ends - no matter by what means - the file, if it still exists, will no longer be locked by the process... because the process does not exist. 程序结束时-不管用什么方式-该文件(如果仍然存在)将不再被进程锁定...因为该进程不存在。

But I have to wonder; 但是我不得不怀疑; if the file is just being deleted anyway at the end, do you really need to create a file in the first place? 如果最后只是删除了文件,您真的需要首先创建一个文件吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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