kardianos / service

Run go programs as a service on major platforms.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Program that install itself: process stuck when cross compile with go 1.19, linux

giter opened this issue · comments

commented

go version > 1.18

When we do cross compile at linux with GOOS=windows go build

The following code may stuck at svc.Run()

The same code works fine with go 1.16, 1.17, 1.18 or just compile on native windows 10.

package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"time"

	"github.com/kardianos/service"
)

type program struct {
	Exec string
	Args []string
	cmd  *exec.Cmd
}

func (p *program) Start(s service.Service) error {

	dir, _ := filepath.Split(p.Exec)
	_ = os.Chdir(dir)

	p.cmd = exec.Command(p.Exec, p.Args...)
	p.cmd.Dir = dir

	return p.cmd.Start()
}

func (p *program) Stop(s service.Service) error {

	if p.cmd != nil && p.cmd.Process != nil {
		_ = p.cmd.Process.Kill()
	}

	if service.Interactive() {
		os.Exit(0)
	}

	return nil
}

func init() {

	if len(os.Args) < 3 {
		return
	}

	var err error

	ctx := os.Args[1]

	if ctx != "service" {
		return
	}

	action := os.Args[2]
	svcName := os.Args[3]

	executable := os.Args[0]

	args := []string{"service", "daemon", svcName}
	if len(os.Args) > 4 {
		args = append(args, os.Args[4:]...)
	}

	prg := &program{
		Exec: executable,
		Args: args,
	}

	svcConfig := &service.Config{
		Name:        svcName,
		DisplayName: svcName,
		Arguments:   args,
	}

	if action == "daemon" {

		args = []string{}
		if len(os.Args) > 4 {
			args = append(args, os.Args[4:]...)
		}

		prg.Args = args

		svc, err := service.New(prg, svcConfig)

		if err != nil {
			panic(err)
		}

		panic(svc.Run())
	}

	svc, err := service.New(prg, svcConfig)
	if err != nil {
		panic(err)
	}

	err = service.Control(svc, action)
	if err != nil {
		panic(err)
	}
	os.Exit(0)
}

func main() {

	for {
		fmt.Println("Hello world!")
		time.Sleep(10 * time.Second)
	}
}

Usage:

program.exe service install program
sc start program
commented

fxied