所以我正在写一个小应用程序,它应该能够自我更新(replace它自己的二进制文件)。
在Windows上执行此操作的最佳方法似乎是:
现在所有这一切工作,我必须能够同步进程之间的状态(能够知道什么时候父母退出),但似乎在golang Windows os.Getppid(而不是syscall.Getppid)没有实现因为它总是返回-1。
我已经看到补丁正在进行,但我不愿意修补我的标准库。
有没有一种简单的方法可以使Getppid在更老版本的Go上工作(也许重新实现它),或者任何人都可以提出一种更好的进程状态同步方法?
想到的东西是绑定在一个套接字上,但这是一个很大的黑客。
也许传递一个pipe道到subprocess,并等待pipe道closures的孩子?
谢谢
父进程可以将PID传递给子进程。
您可以使用命令行参数或环境变量来执行此操作。
你可以使用os.Stdin与exec.Cmd ,现在我没有访问到Windows来测试这个,但是同样的概念应该适用于那里很好:
var child = flag.Bool("child", false, "damn children and their music") func init() { flag.Parse() } func main() { if *child { fmt.Println("child start", time.Now()) // wait until the parent dies and bufio closes the stdin ioutil.ReadAll(os.Stdin) fmt.Println("the parent is dead", time.Now()) time.Sleep(5 * time.Second) fmt.Println("tada\n") } else { fmt.Fprintln(os.Stdout, time.Now()) cmd := exec.Command(os.Args[0], "-child") cmd.Stdout = os.Stdout //not needed in a real program. //this is important, bufio will close after the parent exits, // unlike os.Stdin which screws up, at least on linux cmd.Stdin = bufio.NewReader(os.Stdin) fmt.Println("giving painful birth:", cmd.Start()) time.Sleep(2 * time.Second) } }