Skip to content

Commit

Permalink
Set pgid and kill the process group on posix
Browse files Browse the repository at this point in the history
See https://medium.com/@felixge/killing-a-child-process-and-all-of-its-children-in-go-54079af9477 for a detailed explanation of how this works. For now this only implemented for posix and these changes should have no effect on windows.
This fixes githubnemo#65 and makes the script in githubnemo#72 work (without this fix the script would be terminated on re-compile, but the go executable would continue to run, potentially causing issues with used resources like files and sockets)
  • Loading branch information
ederuiter committed Jul 9, 2022
1 parent 8b56669 commit bd54e6b
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
4 changes: 3 additions & 1 deletion daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ import (
"path/filepath"
"regexp"
"strings"
"syscall"
"time"

"github.com/fatih/color"
Expand Down Expand Up @@ -259,6 +260,7 @@ func logger(pipeChan <-chan io.ReadCloser) {
func startCommand(command string) (cmd *exec.Cmd, stdout io.ReadCloser, stderr io.ReadCloser, err error) {
args := strings.Split(command, " ")
cmd = exec.Command(args[0], args[1:]...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}

if *flagRunDir != "" {
cmd.Dir = *flagRunDir
Expand Down Expand Up @@ -354,7 +356,7 @@ func killProcess(process *os.Process) {
func killProcessHard(process *os.Process) {
log.Println(okColor("Hard stopping the current process.."))

if err := process.Kill(); err != nil {
if err := terminateHard(process); err != nil {
log.Println(failColor("Warning: could not kill child process. It may have already exited."))
}

Expand Down
6 changes: 5 additions & 1 deletion process_posix.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ var fatalSignals = []os.Signal{
}

func terminateGracefully(process *os.Process) error {
return process.Signal(syscall.SIGTERM)
return syscall.Kill(-process.Pid, syscall.SIGTERM)
}

func terminateHard(process *os.Process) error {
return syscall.Kill(-process.Pid, syscall.SIGKILL)
}

func gracefulTerminationPossible() bool {
Expand Down
4 changes: 4 additions & 0 deletions process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ var fatalSignals = []os.Signal{
os.Kill,
}

func terminateHard(process *os.Process) error {
return process.Kill()
}

func terminateGracefully(process *os.Process) error {
return errors.New("terminateGracefully not implemented on windows")
}
Expand Down

0 comments on commit bd54e6b

Please sign in to comment.