溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Golang如何創建守護進程以及平滑重啟

發布時間:2021-05-23 14:57:20 來源:億速云 閱讀:1119 作者:小新 欄目:編程語言

這篇文章主要介紹了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的性能優于其他的解釋性語言,且可以在golang中使用goroutine來實現并發性,它提供了一個非常優雅的goroutine調度程序系統,可以很容易地生成數百萬個goroutine。

感謝你能夠認真閱讀完這篇文章,希望小編分享的“Golang如何創建守護進程以及平滑重啟”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女