gocron/modules/utils/utils_windows.go

53 lines
1.3 KiB
Go
Raw Normal View History

// +build windows
package utils
import (
"syscall"
"os/exec"
"strconv"
2017-05-26 13:59:01 +00:00
"golang.org/x/net/context"
"errors"
)
2017-05-26 13:59:01 +00:00
type Result struct {
output string
err error
}
// 执行shell命令可设置执行超时时间
2017-05-26 13:59:01 +00:00
func ExecShell(ctx context.Context, command string) (string, error) {
2017-05-26 10:09:07 +00:00
cmd := exec.Command("cmd", "/C", command)
// 隐藏cmd窗口
2017-05-26 13:59:01 +00:00
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
}
var resultChan chan Result = make(chan Result)
go func() {
output ,err := cmd.CombinedOutput()
2017-05-26 13:59:01 +00:00
resultChan <- Result{string(output), err}
}()
select {
case <- ctx.Done():
2017-05-29 07:09:41 +00:00
if cmd.Process.Pid > 0 {
exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(cmd.Process.Pid)).Run()
cmd.Process.Kill()
}
2017-05-26 13:59:01 +00:00
return "", errors.New("timeout killed")
case result := <- resultChan:
return ConvertEncoding(result.output), result.err
}
2017-05-26 13:59:01 +00:00
return "", nil
}
2017-05-26 13:59:01 +00:00
func ConvertEncoding(outputGBK string) (string) {
2017-05-26 10:09:07 +00:00
// windows平台编码为gbk需转换为utf8才能入库
outputUTF8, ok := GBK2UTF8(outputGBK)
if ok {
2017-05-26 13:59:01 +00:00
return outputUTF8
2017-05-26 10:09:07 +00:00
}
2017-05-26 13:59:01 +00:00
return "命令输出转换编码失败(gbk to utf8)"
}