Skip to content

Add examples/syscall/syscall #924

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/syscall/syscall/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
app
16 changes: 16 additions & 0 deletions examples/syscall/syscall/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# これは何?

[unix](https://pkg.go.dev/golang.org/x/sys/unix) パッケージの

- Syscall()

を使っているサンプルです。

```sh
$ task
task: [default] rm -f ./app
task: [default] go build -o app .
task: [default] ./app
[syscall] r1=31142, r2=0
[pid ] syscall=31142, os=31142
```
10 changes: 10 additions & 0 deletions examples/syscall/syscall/Taskfile.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# https://taskfile.dev

version: '3'

tasks:
default:
cmds:
- rm -f ./app
- go build -o app .
- ./app
51 changes: 51 additions & 0 deletions examples/syscall/syscall/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//go:build linux

package main

import (
"fmt"
"log"
"os"

"golang.org/x/sys/unix"
)

func main() {
log.SetFlags(0)
if err := run(); err != nil {
log.Fatal(err)
}
}

func run() error {
//
// unix.Syscall() のサンプル
//
// unix.Syscall(), unix.Syscall6() は、指定したシステムコールを呼び出すための関数。
//
// unix.Syscall() は引数が3つ指定できるシステムコール呼び出し関数。
// これより多い場合は6つ指定できる unix.Syscall6() を利用する。
//

//
// getpid(2)
// getpid(2)は引数が無い関数 (pid_t getpid(void);)
//
const (
ZERO uintptr = 0 // unix.Syscall()で指定する際に利用する不要な引数値
)
var (
trap uintptr = unix.SYS_GETPID
r1, r2 uintptr
err unix.Errno // unix.Syscall()の場合は error ではなく unix.Errno であることに注意
)
r1, r2, err = unix.Syscall(trap, ZERO, ZERO, ZERO)
if err != 0 {
return fmt.Errorf("getpid: %d", err)
}

log.Printf("[syscall] r1=%d, r2=%d", r1, r2)
log.Printf("[pid ] syscall=%d, os=%d", r1, os.Getpid())

return nil
}
Loading