Skip to content

Commit 61c9311

Browse files
authored
Merge pull request #835 from devlights/add-unix-forkjoin-example
2 parents 6d7c113 + bc1d89d commit 61c9311

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
app
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# https://taskfile.dev
2+
3+
version: '3'
4+
5+
vars:
6+
APP_NAME: app
7+
8+
tasks:
9+
default:
10+
cmds:
11+
- task: run
12+
build:
13+
cmds:
14+
- go build -o {{.APP_NAME}}{{.exeExt}} .
15+
run:
16+
deps: [ build ]
17+
cmds:
18+
- ./{{.APP_NAME}}{{.exeExt}}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"os"
7+
8+
"golang.org/x/sys/unix"
9+
)
10+
11+
func init() {
12+
log.SetFlags(0)
13+
}
14+
15+
func main() {
16+
if err := run(); err != nil {
17+
log.Fatal(err)
18+
}
19+
}
20+
21+
func run() error {
22+
23+
// forkする前にフラッシュしておく
24+
//
25+
// forkシステムコールが呼ばれる前にバッファに溜まっている場合
26+
// そのバッファが親プロセスと子プロセスの両方にコピーするため
27+
// 両方のプロセスが同じメッセージを出力する可能性があるため。
28+
//
29+
// 実際に以下をコメントアウトした状態で何回か実行すると
30+
// 結果が1つになったり、2つになったりする。
31+
os.Stdout.Sync()
32+
os.Stderr.Sync()
33+
34+
//
35+
// forkシステムコールを呼び出し
36+
//
37+
// 通常の関数のように error が返ってくるのではなく
38+
// syscall.Errno が返ってくることに注意。
39+
pid, _, errno := unix.RawSyscall(unix.SYS_FORK, 0, 0, 0)
40+
if errno != 0 {
41+
return fmt.Errorf("fork failed: %d", errno)
42+
}
43+
44+
switch pid {
45+
case 0:
46+
log.Printf("[%5d] This is the child process.", pid)
47+
default:
48+
log.Printf("[%5d] This is the parent process.", pid)
49+
}
50+
51+
return nil
52+
}

0 commit comments

Comments
 (0)