dongxiusuo9881
2015-12-02 12:54
浏览 693
已采纳

Golang:如何在Linux上使用syscall.Syscall?

There is a very nice description about loading a shared library and calling a function with the syscall package on Windows (https://github.com/golang/go/wiki/WindowsDLLs). However, the functions LoadLibrary and GetProcAddress that are used in this description are not available in the syscall package on Linux. I could not find documentation about how to do this on Linux (or Mac OS).

Thanks for help

图片转代码服务由CSDN问答提供 功能建议

关于在Windows上加载共享库并使用syscall软件包调用函数的很好描述( https://github.com/golang/go/wiki/WindowsDLLs )。 但是,此描述中使用的函数 LoadLibrary GetProcAddress 在Linux上的syscall软件包中不可用。 我找不到有关如何在Linux(或Mac OS)上执行此操作的文档。

感谢您的帮助

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanqinqian5299 2017-04-03 11:41
    已采纳

    Linux syscalls are used directly without loading a library, exactly how depends on which system call you would like to perform. You should refer to the const reference of system calls at https://golang.org/pkg/syscall/

    I will use the Linux syscall getpid() as an example, which returns the process ID of the calling process (our process, in this case).

    According to our reference (link above), in Go this syscall has a uintptr of value 39, and it's listed as SYS_GETPID. In your code you could define a const, e.g. sysGetPid, with value of 39.

    package main
    
    import (
        "fmt"
        "syscall"
    )
    
    func main() {
        pid, _, _ := syscall.Syscall(39, 0, 0, 0)
        fmt.Println("process id: ", pid)
    }
    

    I capture the result of the syscall in pid, this particular call returns no errors so I use blank identifiers for the rest of the returns. Syscall returns two uintptr and 1 error.

    As you can see I can also just pass in 0 for the rest of the function arguments, as I don't need to pass arguments to this syscall.

    The function signature is: func Syscall(trap uintptr, nargs uintptr, a1 uintptr, a2 uintptr, a3 uintptr) (r1 uintptr, r2 uintptr, err Errno)

    For other syscalls you should refer to a system call reference for Linux, e.g. http://man7.org/linux/man-pages/man2/syscalls.2.html, to find out which arguments you need to pass, and what it returns.

    The syscalls have definitions now, so you don't need to use the number code (e.g. "39" as in the example): https://golang.org/pkg/syscall/#pkg-constants

    点赞 打赏 评论

相关推荐 更多相似问题