Created
March 27, 2025 17:16
-
-
Save cdmatta/0422a56f12e13c267e0ec0a5654b4172 to your computer and use it in GitHub Desktop.
External process launch/terminate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
"os/exec" | |
"sync" | |
"syscall" | |
) | |
func main() { | |
var cmd *exec.Cmd | |
var wg sync.WaitGroup | |
running := false | |
reader := bufio.NewReader(os.Stdin) | |
for { | |
fmt.Println("Menu:") | |
fmt.Println("1. Start Application") | |
fmt.Println("2. Stop Application Gracefully (SIGTERM)") | |
fmt.Println("3. Stop Application Immediately (Kill)") | |
fmt.Println("4. Exit") | |
fmt.Print("Enter your choice: ") | |
choice, _ := reader.ReadString('\n') | |
choice = choice[:len(choice)-1] // Remove newline character | |
switch choice { | |
case "1": | |
if running { | |
fmt.Println("Application is already running.") | |
continue | |
} | |
cmd = exec.Command("./simple-hw") | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
if err := cmd.Run(); err != nil { | |
log.Printf("Error running simple-hw: %v", err) | |
} | |
}() | |
running = true | |
fmt.Println("Application started.") | |
case "2": | |
if !running { | |
fmt.Println("Application is not running.") | |
continue | |
} | |
// Send SIGTERM to gracefully stop the application | |
if err := cmd.Process.Signal(syscall.SIGTERM); err != nil { | |
log.Printf("Error stopping application gracefully: %v", err) | |
} else { | |
fmt.Println("Application stopped gracefully.") | |
} | |
wg.Wait() | |
running = false | |
case "3": | |
if !running { | |
fmt.Println("Application is not running.") | |
continue | |
} | |
// Kill the application immediately | |
if err := cmd.Process.Kill(); err != nil { | |
log.Printf("Error stopping application immediately: %v", err) | |
} else { | |
fmt.Println("Application stopped immediately.") | |
} | |
wg.Wait() | |
running = false | |
case "4": | |
if running { | |
fmt.Println("Stopping running application before exiting...") | |
// Kill the application immediately before exiting | |
if err := cmd.Process.Kill(); err != nil { | |
log.Printf("Error stopping application immediately: %v", err) | |
} | |
wg.Wait() | |
} | |
fmt.Println("Exiting program.") | |
return | |
default: | |
fmt.Println("Invalid choice. Please try again.") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment