我如何从 Go 设置 errno

How do I set errno from Go

我有一个 C 函数通过 cgo 调用 Go 例程。我需要 Go 例程来正确设置 errno,以便 C 线程可以检查它的 errno 并采取相应的行动。无法 google 关于如何通过 Go 设置 errno

您不能直接从 go 中引用 errno,请参阅 cgo doesn't like errno on Linux。来自该线程:

I don't know what's wrong, but it doesn't matter since that's not a safe use of errno anyway. Every call into C might happen in a different OS thread, which means that referring to errno directly is not guaranteed to get the value you want.

3880041 开始,尝试引用 C.errno 将引发错误消息:

cannot refer to errno directly; see documentation

一样,从 C 函数设置它是有效的。

澄清一下,您仍然可以通过通过 cgo 调用的 C 函数来设置它。

package main

// #include <errno.h>
// #include <stdio.h>
//
// void setErrno(int err) {
//      errno = err;
// }
//
import "C"

func main() {
        C.setErrno(C.EACCES)
        C.perror(C.CString("error detected"))
        C.setErrno(C.EDOM)
        C.perror(C.CString("error detected"))
        C.setErrno(C.ERANGE)
        C.perror(C.CString("error detected"))
}

在我的系统上它输出

error detected: Permission denied
error detected: Numerical argument out of domain
error detected: Numerical result out of range