Linux系统下串口Close相关实现的深度优化

1. 优化了Close方法的资源释放顺序,先释放独占访问权,再关闭实际的端口句柄
2. 添加了句柄有效性检查,避免对无效句柄进行操作
3. 确保所有资源都能正确清理,包括句柄和信号管道
4. 改进了错误处理机制,确保只返回第一个错误
5. 为所有方法添加了端口状态检查,确保在端口关闭后立即返回PortClosed错误
6. 统一了错误处理格式,使用PortError类型包装系统错误
7. 优化了Read方法的错误处理和超时逻辑
8. 为Write、Break、SetMode、SetDTR、SetRTS和GetModemStatusBits方法添加了端口状态检查
This commit is contained in:
2026-03-03 10:27:03 +08:00
parent f12391c01f
commit 070b7685d5
2 changed files with 275 additions and 41 deletions

View File

@@ -30,35 +30,48 @@ type unixPort struct {
}
func (port *unixPort) Close() error {
// 原子操作检查并设置端口关闭状态
if !atomic.CompareAndSwapUint32(&port.opened, 1, 0) {
return nil
return nil // 端口已经关闭,直接返回
}
// Close port
port.releaseExclusiveAccess()
if err := unix.Close(port.handle); err != nil {
return err
}
var firstErr error
// 发送关闭信号以取消所有待处理的读操作
if port.closeSignal != nil {
// Send close signal to all pending reads (if any)
port.closeSignal.Write([]byte{0})
// Wait for all readers to complete
port.closeLock.Lock()
defer port.closeLock.Unlock()
// Close signaling pipe
if err := port.closeSignal.Close(); err != nil {
return err
if _, err := port.closeSignal.Write([]byte{0}); err != nil && firstErr == nil {
firstErr = err
}
}
return nil
// 检查句柄是否有效,然后执行关闭操作
if port.handle != -1 {
// 释放独占访问权 - 应在关闭handle之前完成
if err := port.releaseExclusiveAccess(); err != nil && firstErr == nil {
firstErr = err
}
// 关闭实际的端口句柄 - 这将解除任何挂起的读写操作
if err := unix.Close(port.handle); err != nil && firstErr == nil {
firstErr = err
}
port.handle = -1 // 标记句柄无效
}
// 关闭信号管道
if port.closeSignal != nil {
if err := port.closeSignal.Close(); err != nil && firstErr == nil {
firstErr = err
}
port.closeSignal = nil // 清除指针
}
return firstErr
}
func (port *unixPort) Read(p []byte) (int, error) {
port.closeLock.RLock()
defer port.closeLock.RUnlock()
// 首先检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
@@ -70,104 +83,157 @@ func (port *unixPort) Read(p []byte) (int, error) {
fds := unixutils.NewFDSet(port.handle, port.closeSignal.ReadFD())
for {
// 在每次select之前再次检查端口状态非阻塞检查
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
timeout := time.Duration(-1)
if port.readTimeout != NoTimeout {
timeout = time.Until(deadline)
if timeout < 0 {
// a negative timeout means "no-timeout" in Select(...)
// 负超时值在Select(...)中表示"无超时"
timeout = 0
}
}
res, err := unixutils.Select(fds, nil, fds, timeout)
if err == unix.EINTR {
continue
continue // 系统调用被中断,重试
}
if err != nil {
return 0, err
// 如果在端口关闭后遇到错误返回PortClosed错误
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
return 0, &PortError{code: FunctionNotImplemented, causedBy: err}
}
if res.IsReadable(port.closeSignal.ReadFD()) {
// 收到关闭信号
return 0, &PortError{code: PortClosed}
}
if !res.IsReadable(port.handle) {
// Timeout happened
return 0, nil
// 超时
if port.readTimeout == NoTimeout {
continue // 无超时设置,继续等待
}
return 0, nil // 返回0字节表示超时
}
n, err := unix.Read(port.handle, p)
if err == unix.EINTR {
continue
continue // 系统调用被中断,重试
}
// Linux: when the port is disconnected during a read operation
// the port is left in a "readable with zero-length-data" state.
// Linux系统特性:当读取操作期间端口断开连接时,
// 端口会进入"可读但返回零长度数据"的状态。
// https://stackoverflow.com/a/34945814/1655275
if n == 0 && err == nil {
return 0, &PortError{code: PortClosed}
}
if n < 0 { // Do not return -1 unix errors
if n < 0 { // 确保不返回负数
n = 0
}
return n, err
// 检查读取操作期间端口是否被关闭
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
if err != nil {
return n, &PortError{code: FunctionNotImplemented, causedBy: err}
}
return n, nil
}
}
func (port *unixPort) Write(p []byte) (n int, err error) {
// 首先检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
n, err = unix.Write(port.handle, p)
if n < 0 { // Do not return -1 unix errors
if n < 0 { // 确保不返回负数
n = 0
}
return
if err != nil {
return n, &PortError{code: FunctionNotImplemented, causedBy: err}
}
return n, nil
}
func (port *unixPort) Break(t time.Duration) error {
// 检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return &PortError{code: PortClosed}
}
if err := unix.IoctlSetInt(port.handle, ioctlTiocsbrk, 0); err != nil {
return err
return &PortError{code: FunctionNotImplemented, causedBy: err}
}
time.Sleep(t)
if err := unix.IoctlSetInt(port.handle, ioctlTioccbrk, 0); err != nil {
return err
return &PortError{code: FunctionNotImplemented, causedBy: err}
}
return nil
}
func (port *unixPort) SetMode(mode *Mode) error {
// 检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return &PortError{code: PortClosed}
}
settings, err := port.getTermSettings()
if err != nil {
return err
return &PortError{code: InvalidSerialPort, causedBy: err}
}
if err := setTermSettingsParity(mode.Parity, settings); err != nil {
return err
}
if err := setTermSettingsDataBits(mode.DataBits, settings); err != nil {
return err
}
if err := setTermSettingsStopBits(mode.StopBits, settings); err != nil {
return err
}
requireSpecialBaudrate := false
if err, special := setTermSettingsBaudrate(mode.BaudRate, settings); err != nil {
return err
} else if special {
requireSpecialBaudrate = true
}
if err := port.setTermSettings(settings); err != nil {
return err
return &PortError{code: InvalidSerialPort, causedBy: err}
}
if requireSpecialBaudrate {
// MacOSX require this one to be the last operation otherwise an
// 'Invalid serial port' error is produced.
// MacOSX要求这是最后一个操作,否则会产生'Invalid serial port'错误
if err := port.setSpecialBaudrate(uint32(mode.BaudRate)); err != nil {
return err
return &PortError{code: InvalidSpeed, causedBy: err}
}
}
return nil
}
func (port *unixPort) SetDTR(dtr bool) error {
// 检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return &PortError{code: PortClosed}
}
status, err := port.getModemBitsStatus()
if err != nil {
return err
return &PortError{code: FunctionNotImplemented, causedBy: err}
}
if dtr {
status |= unix.TIOCM_DTR
@@ -178,9 +244,14 @@ func (port *unixPort) SetDTR(dtr bool) error {
}
func (port *unixPort) SetRTS(rts bool) error {
// 检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return &PortError{code: PortClosed}
}
status, err := port.getModemBitsStatus()
if err != nil {
return err
return &PortError{code: FunctionNotImplemented, causedBy: err}
}
if rts {
status |= unix.TIOCM_RTS
@@ -199,10 +270,16 @@ func (port *unixPort) SetReadTimeout(timeout time.Duration) error {
}
func (port *unixPort) GetModemStatusBits() (*ModemStatusBits, error) {
// 检查端口是否已经关闭
if atomic.LoadUint32(&port.opened) != 1 {
return nil, &PortError{code: PortClosed}
}
status, err := port.getModemBitsStatus()
if err != nil {
return nil, err
return nil, &PortError{code: FunctionNotImplemented, causedBy: err}
}
return &ModemStatusBits{
CTS: (status & unix.TIOCM_CTS) != 0,
DCD: (status & unix.TIOCM_CD) != 0,