Golang: How to use syscall.Syscall on Linux?

霸气de小男生 提交于 2020-08-19 03:49:29

问题


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:


Linux syscalls are used directly without loading a library, exactly how depends on which system call you would like to perform.

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

package main

import (
    "fmt"
    "syscall"
)

func main() {
    pid, _, _ := syscall.Syscall(syscall.SYS_GETPID, 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 more information refer to https://golang.org/pkg/syscall/



来源:https://stackoverflow.com/questions/34043323/golang-how-to-use-syscall-syscall-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!