1 Star 0 Fork 0

DHB / dockerize

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
exec.go 1.52 KB
一键复制 编辑 原始数据 按行查看 历史
package main
import (
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"golang.org/x/net/context"
)
func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...string) {
defer wg.Done()
process := exec.Command(cmd, args...)
process.Stdin = os.Stdin
process.Stdout = os.Stdout
process.Stderr = os.Stderr
// start the process
err := process.Start()
if err != nil {
log.Fatalf("Error starting command: `%s` - %s\n", cmd, err)
}
// Setup signaling
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
wg.Add(1)
go func() {
defer wg.Done()
select {
case sig := <-sigs:
log.Printf("Received signal: %s\n", sig)
signalProcessWithTimeout(process, sig)
cancel()
case <-ctx.Done():
// exit when context is done
}
}()
err = process.Wait()
cancel()
if err == nil {
log.Println("Command finished successfully.")
} else {
log.Printf("Command exited with error: %s\n", err)
// OPTIMIZE: This could be cleaner
os.Exit(err.(*exec.ExitError).Sys().(syscall.WaitStatus).ExitStatus())
}
}
func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal) {
done := make(chan struct{})
go func() {
process.Process.Signal(sig) // pretty sure this doesn't do anything. It seems like the signal is automatically sent to the command?
process.Wait()
close(done)
}()
select {
case <-done:
return
case <-time.After(10 * time.Second):
log.Println("Killing command due to timeout.")
process.Process.Kill()
}
}
1
https://gitee.com/FYMD/dockerize.git
git@gitee.com:FYMD/dockerize.git
FYMD
dockerize
dockerize
master

搜索帮助