Skip to content

Commit 8256433

Browse files
authored
Merge pull request #579 from devlights/add-list-processes-example
2 parents 0f3e6bc + 0ab4727 commit 8256433

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

examples/basic/osop/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55
|file|example name|note|
66
|----|------------|----|
77
|mkdir.go|osop\_mkdir|os.Mkdir/MkdirAllのサンプルです.|
8+
|listprocess.go|osop\_list\_processes|プロセスリストを取得するサンプルです.|

examples/basic/osop/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,5 @@ func NewRegister() mapping.Register {
1414
// Regist -- 登録します.
1515
func (r *register) Regist(m mapping.ExampleMapping) {
1616
m["osop_mkdir"] = Mkdir
17+
m["osop_list_processes"] = ListProcesses
1718
}

examples/basic/osop/listprocess.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package osop
2+
3+
import (
4+
"errors"
5+
"os"
6+
"path/filepath"
7+
"runtime"
8+
9+
"github.com/devlights/gomy/output"
10+
)
11+
12+
// ListProcesses -- プロセスリストを取得するサンプルです.
13+
//
14+
// 本サンプルは Windows では動作しません。
15+
//
16+
// REFERENCES:
17+
// - https://stackoverflow.com/questions/9030680/list-of-currently-running-process-in-go
18+
func ListProcesses() error {
19+
if runtime.GOOS == "windows" {
20+
return errors.New("sorry, this example doesn't run on windows")
21+
}
22+
23+
// Linux 系のOSでは、 /proc ファイルシステムから動作しているプロセスの情報を取得することが出来る.
24+
// PIDは、 /proc/[pid]/exe が、実行ファイルへのシンボリックリンクとなっている.
25+
26+
var (
27+
matches []string
28+
err error
29+
)
30+
31+
matches, err = filepath.Glob("/proc/*/exe")
32+
if err != nil {
33+
return err
34+
}
35+
36+
for _, f := range matches {
37+
// シンボリックリンクの実体取得
38+
real, err := os.Readlink(f)
39+
if err != nil {
40+
// Permission denied は無視
41+
if errors.Is(err, os.ErrPermission) {
42+
continue
43+
}
44+
45+
return err
46+
}
47+
48+
pid := filepath.Base(filepath.Dir(f))
49+
50+
output.Stdoutf("[info]", "name=%v\tpid=%v\n", real, pid)
51+
}
52+
53+
return nil
54+
}

0 commit comments

Comments
 (0)