steve landiss
steve landiss

Reputation: 1913

How do I set errno from Go

I have a C function calling a Go routine via cgo. I need to Go routine to set the errno correctly so the C thread can inspect it's errno and act accordingly. Unable to google on how to set the errno via Go

Upvotes: 2

Views: 1378

Answers (2)

tez
tez

Reputation: 435

Just to clarify, you can still set it via C-function that you call via cgo.

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"))
}

On my system it outputs

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

Upvotes: 3

cnicutar
cnicutar

Reputation: 182694

You can't refer directly to errno from go, see cgo doesn't like errno on Linux. From that thread:

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.

As of 3880041 attempts to refer to C.errno will elicit an error message:

cannot refer to errno directly; see documentation

As pointed out in another answer, setting it from a C function works.

Upvotes: 3

Related Questions