Skip to content

Commit c36a91d

Browse files
committed
Handle exit signals to fg process-compose
1 parent 55f358b commit c36a91d

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

internal/services/manager.go

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"io"
1010
"os"
1111
"os/exec"
12+
"os/signal"
1213
"path/filepath"
1314
"strconv"
1415
"strings"
@@ -167,6 +168,9 @@ func StartProcessManager(
167168
}
168169

169170
func runProcessManagerInForeground(cmd *exec.Cmd, config *globalProcessComposeConfig, port int, projectDir string, w io.Writer) error {
171+
sigs := make(chan os.Signal, 1)
172+
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGTSTP)
173+
170174
if err := cmd.Start(); err != nil {
171175
return fmt.Errorf("failed to start process-compose: %w", err)
172176
}
@@ -186,11 +190,31 @@ func runProcessManagerInForeground(cmd *exec.Cmd, config *globalProcessComposeCo
186190
// We're waiting now, so we can unlock the file
187191
config.File.Close()
188192

189-
err = cmd.Wait()
193+
done := make(chan error, 1)
194+
go func() {
195+
done <- cmd.Wait()
196+
}()
197+
198+
go func() {
199+
for sig := range sigs {
200+
fmt.Printf("Syscall Received: %s\n", sig)
201+
err := syscall.Kill(cmd.Process.Pid, syscall.SIGINT)
202+
if err != nil {
203+
fmt.Fprint(w, "Unable to terminate process-compose cleanly. You may need to manually terminate your services")
204+
}
205+
}
206+
}()
207+
208+
err = <-done
209+
signal.Stop(sigs)
210+
close(sigs)
190211
if err != nil {
191-
if err.Error() == "exit status 1" {
192-
fmt.Fprintf(w, "Process-compose was terminated remotely, %s\n", err.Error())
193-
return nil
212+
var exitErr *exec.ExitError
213+
if errors.As(err, &exitErr) {
214+
if exitErr.ExitCode() == 1 {
215+
fmt.Fprintf(w, "Process-compose was terminated, error: %s\n", exitErr.Error())
216+
return nil
217+
}
194218
}
195219
return err
196220
}
@@ -200,8 +224,9 @@ func runProcessManagerInForeground(cmd *exec.Cmd, config *globalProcessComposeCo
200224
return err
201225
}
202226

203-
config = readGlobalProcessComposeJSON(configFile)
227+
defer configFile.Close()
204228

229+
config = readGlobalProcessComposeJSON(configFile)
205230
delete(config.Instances, projectDir)
206231
return writeGlobalProcessComposeJSON(config, configFile)
207232
}

0 commit comments

Comments
 (0)