go调用exe

新建一个demo

新建demo.go

package main

import (
	"log"
	"os"
	"time"
)

func main() {

	logFile, err := os.OpenFile("C:\\Users\\14784\\Desktop\\demo.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		panic(err)
	}
	log.SetOutput(logFile) // 将文件设置为log输出的文件

	for{
		log.Println("running...")
		time.Sleep(time.Duration(1)*time.Second)
	}
}

编译

go build demo.go

简单调用exe

新建exec_test.go

package main

import (
	"os/exec"
	"testing"
	"fmt"
)

//简单测试
func TestSimple(t *testing.T){
	fmt.Println("test simple")
	cmd := exec.Command("D:\\xzw\\demo\\go\\exec\\demo.exe")
	out, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(out))
}

测试

go test -v -run=TestSimple exec_test.go 

添加结束指令

//添加退出
func TestCancel(t *testing.T){
	state := true
	fmt.Println("test cancel")
	go func() {
		ctx, cancel := context.WithCancel(context.Background())
		cmd := exec.CommandContext(ctx,"D:\\xzw\\demo\\go\\exec\\demo.exe")
		cmd.Start()
		for{
			if state{
				continue
			}
			fmt.Println("cancel demo")
			cancel()
			break
		}
		cmd.Wait()
	}()


	time.Sleep(time.Second*10)
	state=false
	fmt.Println("end exec!")

	for{
		time.Sleep(time.Second*1)
	}
}

测试

go test -v -run=TestCancel exec_test.go 

测试结果

10s后退出exe

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×