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

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

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog