作为一名 PHP 开发老兵。使用过命令行对 nginx、PHP-FPM 进行启动/重启/停止等操作。印象非常深刻。让我用 C/C++ 开发这样的系统肯定是没精力搞了。然而,自从 Golang 进入了我的视野之后。我发现这一切都变得非常的容易。
1)生成守护进程
直接上代码:
package main import ( "os" "os/exec" "path/filepath" ) func main() { //判 断当其是否是子进程,当父进程return之后,子进程会被 系统1 号进程接管 if os.Getppid() != 1 { // 将命令行参数中执行文件路径转换成可用路径 filePath, _ := filepath.Abs(os.Args[0]) cmd := exec.Command(filePath, os.Args[1:]...) // 将其他命令传入生成出的进程 cmd.Stdin = os.Stdin // 给新进程设置文件描述符,可以重定向到文件中 cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Start() // 开始执行新进程,不等待新进程退出 return } }
对 Linux 系统熟悉的人应该知道:用户创建的守护进程会被 Linux 系统的 1 号进程接管。换句话说,上面的代码只能在 Linux 系统运行。Unix 系统我没有玩过。所以,也不能给出具体的建议。
我在网上看到还有其他的方法实现守护进程的创建。但是,我觉得只有上面源码的方式我觉得不错。并且成功用于项目当中。
比如:
os.StartProcess() 创建守护进程。 syscall.RawSyscall() 创建守护进程。
唯独 exec.Command
创建守护进程的方式最高级。封装得最好。推荐使用这种试。
2) 守护进程启动/重启/停止
在第 1 点当中,我们已经成功启动了一个守护进程。但是,我们不可能使用 kill 命令去结束它。然后,再启动吧。所以,我们要用业界专业的手法:信号。
任何进程在运行中都能接收到我们发送给它的信号。关于 Linux 的信号有很多。大家可以自己 Google 搜索关键词:Linux 信号。
直接上源码:
package main import "fmt" import "os" import "os/signal" import "syscall" func main() { // Go signal notification works by sending `os.Signal` // values on a channel. We'll create a channel to // receive these notifications (we'll also make one to // notify us when the program can exit). sigs := make(chan os.Signal, 1) done := make(chan bool, 1) // `signal.Notify` registers the given channel to // receive notifications of the specified signals. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) // This goroutine executes a blocking receive for // signals. When it gets one it'll print it out // and then notify the program that it can finish. go func() { sig := <-sigs fmt.Println() fmt.Println(sig) done <- true }() // The program will wait here until it gets the // expected signal (as indicated by the goroutine // above sending a value on `done`) and then exit. fmt.Println("awaiting signal") <-done fmt.Println("exiting") }
有三个关键点:
1)注册信号
2)接收信号
3)处理信号。
只要把创建守护进程与信号量处理整合一起,就能实现命令去管理守护进程了。
更多golang相关技术文章,请访问golang教程栏目!
以上是解析Golang怎么创建守护进程和平滑重启的详细内容。更多信息请关注PHP中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

记事本++7.3.1
好用且免费的代码编辑器