Bad File Descriptor Encountered While Attempting File Append
When attempting to append to a logging file within a Go routine, you may encounter the error "write ./log.log: bad file descriptor". Despite the file's existence and appropriate permissions (666), this issue persists.
Initially, the cause was suspected to be concurrent file access by multiple go routines. However, implementing a mutex failed to resolve the issue.
Solution
The resolution lies in adding the O_WRONLY flag during file opening:
if f, err := os.OpenFile("./log.log", os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil { /*[...]*/ }
Explanation
According to the Linux documentation for open, one of three access modes (O_RDONLY, O_WRONLY, or O_RDWR) must be specified. These modes request opening the file as read-only, write-only, or read/write, respectively.
By default, the file descriptor is opened in read-only mode, as confirmed by the following code in /usr/local/go/src/syscall/zerrors_linux_amd64.go:
O_RDONLY = 0x0 O_RDWR = 0x2 O_WRONLY = 0x1
Therefore, explicitly specifying O_WRONLY ensures that the file is opened in write-only mode, resolving the initial issue.
The above is the detailed content of Why Does Appending to a File Result in a 'Bad File Descriptor' Error in Go?. For more information, please follow other related articles on the PHP Chinese website!