在Go 中運行命令並將其從進程中分離
問題:
你想要執行一個長-在Golang 中運行進程,同時滿足以下幾個要求:
- 將進程的標準輸出重定向到檔案
- 控制進程的使用者
- 防止進程在以下情況下死亡你的程式退出
- 避免進程成為殭屍
- 取得正在運行的進程的PID
嘗試的解決方案:
您嘗試了使用exec.Command 的解決方案,但它不滿足所有要求,特別是當您的程式收到SIGTERM/SIGKILL 訊號時。
要理解的要點:
需要注意的是,一旦啟動進程,您就無法更改其父進程 - 進程的父子關係是固定的。
替代庫:
建議使用解決此問題的現有庫,而不是重新發明輪子。建議使用以下函式庫:
- https://github.com/hashicorp/go-reap
- https://github.com/krallin/tini
- https://busybox.net/
- https://software.clapper.org/daemonize/
- https://wiki.gentoo.org/wiki/OpenRC
- https://www.freedesktop.org/wiki/Software/systemd/
使用go-reap 的範例:
<code class="go">import ( "fmt" "os" "os/exec" "strings" "sync" "time" "github.com/fatih/color" "github.com/hashicorp/go-reap" ) func main() { if reap.IsSupported() { done := make(chan struct{}) var reapLock sync.RWMutex pids := make(reap.PidCh, 1) errors := make(reap.ErrorCh, 1) go reap.ReapChildren(pids, errors, done, &reapLock) go report(pids, errors, done) // Here is where you would start your long-running process Sh() close(done) } else { fmt.Println("Sorry, go-reap isn't supported on your platform.") } } func report(pids reap.PidCh, errors reap.ErrorCh, done chan struct{}) { sprintf := color.New(color.FgWhite, color.Bold).SprintfFunc() for ;; { select { case pid := = 1 { if args[0] == "-c" { script = args[1:] } } if len(script) == 0 { fn.CyanBold("cmd: expecting sh -c 'foobar'") os.Exit(111) } var cmd *exec.Cmd parts, _ := shlex.Split(strings.Join(script, " ")) if len(parts) >= 2 { cmd = fn.Merge(exec.Command(parts[0], parts[1:]...), nil) } if len(parts) == 1 { cmd = fn.Merge(exec.Command(parts[0]), nil) } // ... Here you can customize how the process is started and controlled if fn.IfEnv("HANG") { fn.CyanBold("cmd: %v\n start", parts) ex := cmd.Start() if ex != nil { fn.CyanBold("cmd %v err: %s", parts, ex) } go func() { time.Sleep(time.Millisecond * 100) errw := cmd.Wait() if errw != nil { fn.CyanBold("cmd %v err: %s", parts, errw) } else { fn.CyanBold("cmd %v all done.", parts) } }() fn.CyanBold("cmd: %v\n dispatched, hanging forever (i.e. to keep docker running)", parts) for { time.Sleep(time.Millisecond * time.Duration(fn.EnvInt("HANG", 2888))) fn.SystemCyan("/bin/ps", "-e", "-o", "stat,comm,user,etime,pid,ppid") } } else { if fn.IfEnv("NOWAIT") { ex := cmd.Start() if ex != nil { fn.CyanBold("cmd %v start err: %s", parts, ex) } } else { ex := cmd.Run() if ex != nil { fn.CyanBold("cmd %v run err: %s", parts, ex) } } fn.CyanBold("cmd %v\n dispatched, exit docker.", parts) } }</code>
此範例使用go-reap 啟動shell(Sh() 函數)並在該shell 中執行命令。它設定收割機來處理子進程的清理。
透過使用信譽良好的函式庫,您可以避免常見的陷阱並確保您的應用程式能如預期運作。
以上是如何在 Golang 中執行長時間運行的進程並將其與我的程式分離,同時控制使用者、重定向輸出並防止其成為殭屍進程?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Tousethe"encoding/binary"packageinGoforencodinganddecodingbinarydata,followthesesteps:1)Importthepackageandcreateabuffer.2)Usebinary.Writetoencodedataintothebuffer,specifyingtheendianness.3)Usebinary.Readtodecodedatafromthebuffer,againspeci

encoding/binary包提供了統一的方式來處理二進制數據。 1)使用binary.Write和binary.Read函數可以編碼和解碼整數、浮點數等多種數據類型。 2)可以通過實現binary.ByteOrder接口來處理自定義類型。 3)需要注意字節序選擇、數據對齊和錯誤處理,以確保數據的正確性和高效性。

Go的strings包不適用於所有用例。它適用於大多數常見的字符串操作,但對於復雜的NLP任務、正則表達式匹配和特定格式解析,可能需要第三方庫。

Go語言中的strings包在處理大量字符串操作時存在性能和內存使用上的限制。 1)性能問題:如strings.Replace和strings.ReplaceAll在處理大規模字符串替換時效率較低。 2)內存使用:由於字符串不可變,每次操作會生成新對象,導致內存消耗增加。 3)Unicode處理:在處理複雜Unicode規則時不夠靈活,可能需要藉助其他包或庫。

掌握Go語言中的strings包可以提高文本處理能力和開發效率。 1)使用Contains函數檢查子字符串,2)用Index函數查找子字符串位置,3)Join函數高效拼接字符串切片,4)Replace函數替換子字符串。注意避免常見錯誤,如未檢查空字符串和大字符串操作性能問題。

你應該關心Go語言中的strings包,因為它能簡化字符串操作,使代碼更清晰高效。 1)使用strings.Join高效拼接字符串;2)用strings.Fields按空白符分割字符串;3)通過strings.Index和strings.LastIndex查找子串位置;4)用strings.ReplaceAll進行字符串替換;5)利用strings.Builder進行高效字符串拼接;6)始終驗證輸入以避免意外結果。

thestringspackageingoisesential forefficientstringManipulation.1)itoffersSimpleyetpoperfulfunctionsFortaskSlikeCheckingSslingSubstringsStringStringsStringsandStringsN.2)ithandhishiCodeDewell,withFunctionsLikestrings.fieldsfieldsfieldsfordsforeflikester.fieldsfordsforwhitespace-fieldsforwhitespace-separatedvalues.3)3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版
SublimeText3 Linux最新版

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中