Why Does Appending to a File Result in a 'Bad File Descriptor' Error in Go?

Susan Sarandon
Release: 2024-11-11 15:56:03
Original
722 people have browsed it

Why Does Appending to a File Result in a

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 { /*[...]*/ }
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template