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

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

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

报告相同问题?