Brian
Brian

Reputation: 1025

Safely close a file descriptor in golang

Another question How to read/write from/to file using Go? got into safe closing of file descriptors in a comment.

Note that these examples aren't checking the error return from fo.Close(). From the Linux man pages close(2): Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota. – Nick Craig-Wood Jan 25 '13 at 7:12

The solution that updated the post used a panic:

// close fo on exit and check for its returned error
defer func() {
    if err := fo.Close(); err != nil {
        panic(err)
    }
}()

I want to hand this error as a value instead of panicking.

Upvotes: 3

Views: 9570

Answers (1)

Brian
Brian

Reputation: 1025

If we are afraid of writes not being completed close isn't enough, so updating the error is still not correct.

The correct solution if you want to not hit this is to fsync the file(s):

defer(fd.Close())
// Do stuff
return fd.Sync()

It's easier to read then returning a non-nil modified error either through defer or maintaining throughout the function.

This will be a performance hit, but will catch both close errors for writing to buffers and the physical write to disk.

Upvotes: 5

Related Questions