Skip to content

Commit 04e7b71

Browse files
author
Adriano Santos
committed
feat: added support to trap os signals
1 parent cb445b1 commit 04e7b71

File tree

5 files changed

+40
-6
lines changed

5 files changed

+40
-6
lines changed

tools/sdk-init/bin/sdk-init

12 KB
Binary file not shown.

tools/sdk-init/cmd/main.go

+34-4
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,55 @@ package main
33
import (
44
"log"
55
"os"
6+
"os/signal"
7+
"syscall"
68

79
"sdk-init/pkg/copier"
810
"sdk-init/pkg/runner"
911
)
1012

1113
func main() {
12-
srcDir := "/protos"
13-
destDir := "/shared/protos"
14+
srcDir := getEnv("SRC_DIR", "/protos")
15+
destDir := getEnv("DEST_DIR", "/shared/protos")
1416

1517
if err := copier.CopyDir(srcDir, destDir); err != nil {
1618
log.Fatalf("Error copying files: %v", err)
1719
}
1820
log.Println("Files copied successfully.")
1921

22+
// Configure the channel to capture system signals
23+
sigChan := make(chan os.Signal, 1)
24+
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
25+
2026
if len(os.Args) > 1 {
21-
if err := runner.RunCommand(os.Args[1], os.Args[2:]...); err != nil {
22-
log.Fatalf("Error executing command: %v", err)
27+
cmd, err := runner.RunCommandAsync(os.Args[1], os.Args[2:]...)
28+
if err != nil {
29+
log.Fatalf("Error starting command: %v", err)
30+
}
31+
32+
// Waits for signals and passes to subprocess
33+
go func() {
34+
sig := <-sigChan
35+
log.Printf("Received signal: %v. Forwarding to subprocess...", sig)
36+
if err := cmd.Process.Signal(sig); err != nil {
37+
log.Printf("Error forwarding signal to subprocess: %v", err)
38+
}
39+
}()
40+
41+
// Wait for the subprocess to finish...
42+
if err := cmd.Wait(); err != nil {
43+
log.Fatalf("Subprocess terminated with error: %v", err)
44+
} else {
45+
log.Println("Subprocess terminated successfully.")
2346
}
2447
} else {
2548
log.Println("No command specified. Finishing...")
2649
}
2750
}
51+
52+
func getEnv(key, defaultValue string) string {
53+
if value, exists := os.LookupEnv(key); exists {
54+
return value
55+
}
56+
return defaultValue
57+
}

tools/sdk-init/example-app/sdk-init

1.39 MB
Binary file not shown.

tools/sdk-init/example-app/shared/empty

Whitespace-only changes.

tools/sdk-init/pkg/runner/runner.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@ import (
55
"os/exec"
66
)
77

8-
func RunCommand(cmd string, args ...string) error {
8+
func RunCommandAsync(cmd string, args ...string) (*exec.Cmd, error) {
99
command := exec.Command(cmd, args...)
1010
command.Stdout = os.Stdout
1111
command.Stderr = os.Stderr
1212

13-
return command.Run()
13+
if err := command.Start(); err != nil {
14+
return nil, err
15+
}
16+
17+
return command, nil
1418
}

0 commit comments

Comments
 (0)