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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料