Skip to content

Commit c3f1e35

Browse files
authored
Merge pull request #837 from devlights/add-unix-fork-forkexec-example
2 parents 0483f86 + 68da9ee commit c3f1e35

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-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: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//go:build linux
2+
3+
package main
4+
5+
import (
6+
"fmt"
7+
"log"
8+
"os"
9+
"path/filepath"
10+
"syscall"
11+
)
12+
13+
func init() {
14+
log.SetFlags(0)
15+
}
16+
17+
func main() {
18+
if err := run(); err != nil {
19+
log.Fatal(err)
20+
}
21+
}
22+
23+
func run() error {
24+
var (
25+
abs, _ = filepath.Abs(".")
26+
bin = "/bin/ls"
27+
args = []string{bin, "-lh", abs}
28+
envs = []string{"PATH=/usr/bin:/bin"}
29+
attr = syscall.ProcAttr{
30+
Dir: abs,
31+
Env: envs,
32+
Files: []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()},
33+
}
34+
35+
pid int
36+
err error
37+
status syscall.WaitStatus
38+
)
39+
if pid, err = syscall.ForkExec(bin, args, &attr); err != nil {
40+
return fmt.Errorf("ForkExec() failed: %w", err)
41+
}
42+
43+
log.Printf("[%5d] Child process started", pid)
44+
45+
if _, err = syscall.Wait4(pid, &status, 0, nil); err != nil {
46+
return fmt.Errorf("Wait4() failed: %w", err)
47+
}
48+
49+
if status.Exited() {
50+
log.Printf("[%5d] Child process exited with status: %d", pid, status.ExitStatus())
51+
} else {
52+
log.Printf("[%5d] Child process did not exit normally: %d", pid, status.ExitStatus())
53+
}
54+
55+
return nil
56+
}

0 commit comments

Comments
 (0)