Preventing Ctrl C from Disrupting exec.Command in Golang
When executing commands using exec.Command, it's crucial to be aware of the potential for Ctrl C interruptions, even if signal.Notify has been utilized to intercept such signals. This issue can be observed in the following example:
package main import ( "log" "os" "os/exec" "os/signal" "syscall" ) func sleep() { log.Println("Sleep start") cmd := exec.Command("sleep", "60") cmd.Run() log.Println("Sleep stop") } func main() { var doneChannel = make(chan bool) go sleep() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) signal.Notify(c, syscall.SIGTERM) go func() { <-c log.Println("Receved Ctrl + C") }() <-doneChannel }
Upon pressing Ctrl C while the program is running, the output indicates that the "sleep" command gets interrupted, even though the main program continues to run:
2015/10/16 10:05:50 Sleep start ^C2015/10/16 10:05:52 Receved Ctrl + C 2015/10/16 10:05:52 Sleep stop
The key to resolving this issue lies in recognizing that the shell signals the entire process group when Ctrl C is pressed. This behavior can be prevented by starting the command in its own process group using the Setpgid and Pgid fields in syscall.SysProcAttr:
cmd := exec.Command("sleep", "60") cmd.SysProcAttr = &syscall.SysProcAttr{ Setpgid: true, }
By incorporating this modification, the "sleep" command will no longer be interrupted by Ctrl C, allowing it to continue running independently.
The above is the detailed content of How Can I Prevent Ctrl C from Interrupting `exec.Command` in Go?. For more information, please follow other related articles on the PHP Chinese website!