4 ms·
I come across this all the time; usually it can be handled well with RAII or similar, in languages with the prerequisites. Consider a simple case where I am tr
by dllthomas 6y ago
I come across this all the time; usually it can be handled well with RAII or similar, in languages with the prerequisites.
Consider a simple case where I am trying to receive data over a socket and write it to a file. I need to 1) open the socket, and 2) open the file. Whichever order I do these in, if the second one fails I need to be sure I clean up the former.
- WesolyKubeczek 6y agoHow can you be sure your cleanups worked? Use a protocol that can cope with a disconnect well. Write to a temporary file which either you then rename, or the OS discards if there was a failure. Trying to “clean up” manually can break things further since you don’t and can’t account for all possible reasons for a failure. A simple example: your hard drive is failing, and performing any kinds of cleanups on it will get your program stuck even further. Also, does it really matter too much for your stated purpose if you get an ENOSPC, an EPERM, or an EIO?
- dllthomas 6y agoYou're over-complicating it. The cleanup I was describing is freeing resources that had been allocated to the process before the error. Sure, in a sufficiently crazy situation, close() might not actually close the file descriptor - maybe I've somehow trampled on the memory associated with the function (having worked around any kind of W^X), or maybe the operating system is just seriously fucked - but it seems crazy to expect that on the basis of failing to open a file. You should still close the socket.