使golang程序重新启动自身

huangapple go评论72阅读模式
英文:

Make golang program restart itself

问题

我正在编写一个工具,其中一个命令允许你启动一个新的会话。

你想知道如何使一个 Golang 程序重新启动自身?如果你的解决方案是基于操作系统的,我使用的是 Linux。

我尝试了以下代码:

// 导入 os/exec 包
exec.Command(os.Args[0]).Run()

但是它不起作用。我得到了一个空白的输入会话,很难解释。

我的程序输入:session new
:(
:(

每个 使golang程序重新启动自身 代表一个空行,我可以在其中输入内容并按回车键,这里有两个 :(,表示我按了两次回车键。

我期望的输出是:

我的程序输入:session new
我的程序输入:

编辑:更准确地说,我想创建一个相同程序的子进程。

英文:

Im writing a tool and one of its commands allows you to start a new session

How can I make a golang program restart itself? If your solution is OS-Strict im on Linux.

I tried

// exec from os/exec
exec.Command(os.Args[0]).Run()

but it doesnt work. I get a blank input session which is hard to explain

My Program Input:  session new
:(
:(

each of the 使golang程序重新启动自身 represent a blank line where im able to type stuff and hit enter, there are 2 which means i hit enter twice

Im expecting

My Program Input: session new
My Program Input: 

Edit: more accurately, i want to make a subprocess of the same program

答案1

得分: 1

你可以使用一个独立的进程,比如radovskyb/gobeat

示例:

sudo gobeat -pid=1234 -cmd="go run sendemail.go"

  1. 使用sudo运行,这样gobeat将在同一个终端tty中重新启动服务器。(sudo
  2. gobeat指向你想要监视的正在运行的服务器进程。(gobeat -pid=1234
  3. 设置cmd标志以运行一个发送电子邮件通知服务器已重新启动的Go文件。(-cmd="go run sendemail.go"

如果你不想使用一个独立的进程,可以考虑实现优雅升级

使golang程序重新启动自身

你可以使用库cloudflare/tableflip

英文:

You could use a separate process, like radovskyb/gobeat.
Example:
> sudo gobeat -pid=1234 -cmd="go run sendemail.go"
>
> 1. Run with sudo so gobeat will restart the server in the same terminal tty that it originated in. (sudo)
> 2. Point gobeat to the process of the running server that you want gobeat to monitor. (gobeat -pid=1234)
> 3. Set the cmd flag to run a Go file that will send an email notifying you that the server was restarted. (-cmd="go run sendemail.go")

If you do not want a separate process, then consider implementing a graceful upgrade

使golang程序重新启动自身

You can use the library cloudflare/tableflip for instance.

huangapple
  • 本文由 发表于 2022年11月23日 13:39:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/74542227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定