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

huangapple go评论82阅读模式
英文:

Golang: How to use syscall.Syscall on Linux?

问题

这里有一个非常好的关于在Windows上使用syscall包加载共享库并调用函数的描述(https://github.com/golang/go/wiki/WindowsDLLs)。然而,在Linux上的syscall包中并没有提供在该描述中使用的LoadLibraryGetProcAddress函数。我找不到关于如何在Linux(或Mac OS)上实现这一功能的文档。

谢谢帮助。

英文:

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

得分: 9

Linux系统调用可以直接使用,而无需加载库,具体取决于您想执行的系统调用。

我将以使用Linux系统调用getpid()为例,该调用返回调用进程(在本例中为我们的进程)的进程ID。

package main

import (
	"fmt"
	"syscall"
)

func main() {
	pid, _, _ := syscall.Syscall(syscall.SYS_GETPID, 0, 0, 0)
	fmt.Println("进程ID:", pid)
}

我将系统调用的结果捕获在pid中,这个特定的调用不返回错误,所以我使用空标识符来表示其他返回值。Syscall返回两个uintptr和1个错误。

正如您所看到的,我也可以将其余的函数参数设置为0,因为我不需要向此系统调用传递参数。

函数签名为:func Syscall(trap uintptr, nargs uintptr, a1 uintptr, a2 uintptr, a3 uintptr) (r1 uintptr, r2 uintptr, err Errno)。

有关更多信息,请参阅https://golang.org/pkg/syscall/。

英文:

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/

huangapple
  • 本文由 发表于 2015年12月2日 20:54:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/34043323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定