Let's assume we have a process that allocates a socket listening on a specific port, does something with it and then terminates abnormaly. Now a second process starts and wants to allocate a socket listening on the same port that was previously held by the crahsed process. Is this socket available for re-allocation?
开发者_JAVA技巧How does the Operating System recover resources that weren't released properly? Does the OS track the process id along with each allocated resource?
Is this cleanup something I can expect every POSIX compliant system to do?
This is up to the operating system but generally an OS maintains a process control structure to, among other things, manage its resources. When a process allocates a resource from the system (such as opening a file or allocating memory), details of the allocation are placed in that structure. When the process terminates, anything left in it gets cleaned up - but it's best to explicitly clean up as you go.
Specific details will depend upon the operating system, but generally speaking user-code is run in a virtual address space/sandbox where it does not have any direct access to hardware resources. Anything that the user process wants to access/allocate must be provided by calling the OS and asking it for the desired resource.
Thus the OS has a simple way of knowing who has been allocated which resources, and as long as it keeps track of this information, cleaning up resources in the event of a crashed process is as simple as fetching the list of resources allocated to that process, and marking them all as available again.
精彩评论