dpojoxa5613 2015-01-23 21:45
浏览 59
已采纳

如何将syscall.Errno传递给os.Exit?

Let's say I try to acquire a lock, fail, and want to exit the program.

err = syscall.Flock(lockfd, syscall.LOCK_EX|syscall.LOCK_NB)
if err == syscall.EAGAIN {
    os.Exit(err)
}

The problem is you need to pass an integer to os.Exit.

I've tried:

os.Exit(int(err))
os.Exit(syscall.EAGAIN)

// Compiles fine, but the cast fails.. no idea why
eerr, _ := err.(*syscall.Errno); os.Exit(int(*eerr)) 

// panics
reflect.ValueOf(err).Int()

It seems like you can compare the syscall.Errno to other integers, but actually trying to get the value of it is escaping me...

  • 写回答

2条回答 默认 最新

  • douxinghuai3150 2015-01-23 21:51
    关注

    You can normally just convert a syscall.Errno to an int

    if err == syscall.EAGAIN {
        os.Exit(int(err))
    }
    

    syscall.Errno is defined as a uintptr, which can be converted directly to an int. There's no interface, assertion, or reflection involved.

    But when receiving it as an error interface, you need to assert it first.

    if err == syscall.EAGAIN {
        os.Exit(int(err.(syscall.Errno)))
    }
    

    The syscall.Errno is used as a value, not a pointer, no need to try and dereference it with *.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题