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

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?