When attempting to append to a logging file within a Go routine, users may encounter the following error:
write ./log.log: bad file descriptor
Despite ensuring that the target file exists and has the appropriate permissions, the issue persists. Initial attempts to resolve the issue using a mutex failed.
The resolution lies in adding the O_WRONLY flag to the os.OpenFile call:
if f, err := os.OpenFile("./log.log", os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil { /*[...]*/ }
According to the Linux documentation on open, one of the following access modes must be included in the flags argument: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file in read-only, write-only, or read/write mode, respectively.
By default, Go's os.OpenFile call opens the file in read-only mode. As such, it is necessary to explicitly specify O_WRONLY to allow writing to the logging file.
The above is the detailed content of Why is the `os.OpenFile` function throwing a 'bad file descriptor' error when appending to a log file in Go?. For more information, please follow other related articles on the PHP Chinese website!