How to restart self?

I have code:

package main

import (
	"os"
	"fmt"
)

func main() {
	if len(os.Args) == 2 {
		fmt.Print("input:")
		var s string
		for {
			fmt.Scanln(&s)
			if s != "" {
				break
			}
		}
		fmt.Printf("output:%s", s)
	} else {
		restart()
	}
}

func restart() {
	procAttr := new(os.ProcAttr)
	procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
	os.StartProcess(os.Args[0], []string{"", "test"}, procAttr)
}

I can use this method in the Windows GUI program to achieve an automatic restart after the update, but in the Linux-like restart after the terminal output and similar HTTP Server services can work properly, but can not get input from the terminal.
Indeed, for the procedures do not need to receive the terminal input, this method is no problem, but need to restart can still receive input from the terminal information, this method is not applicable, I would like to know whether this is a system or other reasons? After all, after the restart the program output information and port monitoring and so can work properly.

github.com/jpillora/overseer might be what you are looking for:

package main

import (
	"fmt"

	"github.com/jpillora/overseer"
)

func main() {
	overseer.Run(overseer.Config{
		Program: prog,
	})
}

func prog(overseer.State) {
	fmt.Print("input:")
	var s string
	for {
		fmt.Scanln(&s)
		if s != "" {
			break
		}
	}
	fmt.Printf("output:%s\n", s)

	overseer.Restart()
}

It can also handle updating the binary (including binary diffs).

If you need a complete packaging and distribution solution, look at https://equinox.io.

1 Like

I try the code

package main

import (
	"fmt"

	"github.com/jpillora/overseer"
)

func main() {
	overseer.Run(overseer.Config{
		Program: prog,
		Debug: true,
	})
}

func prog(overseer.State) {
	fmt.Print("input:")
	var s string
	fmt.Scanln(&s)
	fmt.Printf("output:%s\n", s)

	//overseer.Restart()
}

on linux,ok,but on windows output:
2017/04/05 12:01:24 [overseer master] run
2017/04/05 12:01:24 [overseer master] starting C:\Users\xxxx\Desktop\restartself.exe
2017/04/05 12:01:24 [overseer slave#1] run
2017/04/05 12:01:24 [overseer slave#1] start program
2017/04/05 12:01:24 [overseer master] prog exited with 1

I don’t have a windows machine to test on, and don’t see why it doesn’t work. Raise an issue to get help figuring it out.

In the mean time, you could use build tags to use your method on windows and overseer on linux.

Thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.