golang代碼中調(diào)用Linux命令
更新時間:2023年02月19日 09:47:51 作者:taotaozh
本文主要介紹了golang代碼中調(diào)用Linux命令,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
傳統(tǒng)方案--crontab
- 缺點
- 配置任務(wù)時,需要SSh登錄腳本服務(wù)器進(jìn)行操作
- 服務(wù)器宕機(jī),任務(wù)將終止調(diào)度,需要人工遷移
- 排查問題低效,無法方便的查看任務(wù)狀態(tài)與錯誤輸出
分布式任務(wù)調(diào)度
- 優(yōu)點
- 可視化Web后臺,方便進(jìn)行任務(wù)管理
- 分布式架構(gòu)、集群化調(diào)度,不存在單點故障
- 追蹤任務(wù)執(zhí)行狀態(tài),采集任務(wù)輸出,可視化log查看
go執(zhí)行shell命令
1、執(zhí)行程序:/usr/bin/python start.py
2、調(diào)用命令: cat nginx.log | grep "2022"
- bash模式
- 交互模式:ls -l
- 非交互模式:/bin/bash -c "ls -l" ------ 我們使用這個
- bash模式
實際我們在golang代碼中調(diào)用Linux命令
1、普通調(diào)用
package main
import (
"fmt"
"os/exec"
)
var (
output []byte
err error
)
func main() {
// 要執(zhí)行的命令
cmd := exec.Command("bash.exe", "-c", "echo 111")
// CombinedOutput-->捕獲異常跟命令輸出的內(nèi)容
if output, err = cmd.CombinedOutput(); err != nil {
fmt.Println("error is :", err)
return
}
// 打印輸出結(jié)果
fmt.Println(string(output))
}
2、結(jié)合協(xié)程調(diào)用,可控制中斷調(diào)用
package main
import (
"context"
"fmt"
"os/exec"
"time"
)
// 接收子協(xié)程的數(shù)據(jù),協(xié)程之間用chan通信
type result struct {
output []byte
err error
}
func main() {
// 執(zhí)行一個cmd,讓他在一個攜程里面執(zhí)行2s,
// 1s的時候 殺死cmd
var (
ctx context.Context
cancelFunc context.CancelFunc
cmd *exec.Cmd
resultChan chan *result
res *result
)
// 創(chuàng)建一個結(jié)果隊列
resultChan = make(chan *result, 1000)
/*
1. WithCancel()函數(shù)接受一個 Context 并返回其子Context和取消函數(shù)cancel
2. 新創(chuàng)建協(xié)程中傳入子Context做參數(shù),且需監(jiān)控子Context的Done通道,若收到消息,則退出
3. 需要新協(xié)程結(jié)束時,在外面調(diào)用 cancel 函數(shù),即會往子Context的Done通道發(fā)送消息
4. 注意:當(dāng) 父Context的 Done() 關(guān)閉的時候,子 ctx 的 Done() 也會被關(guān)閉
*/
ctx, cancelFunc = context.WithCancel(context.TODO())
// 起一個協(xié)程
go func() {
var (
output []byte
err error
)
// 生成命令
cmd = exec.CommandContext(ctx, "bash", "-c", "sleep 3;echo hello;")
// 執(zhí)行命令cmd.CombinedOutput(),且捕獲輸出
output, err = cmd.CombinedOutput()
// 用chan跟主攜程通信,把任務(wù)輸出結(jié)果傳給main協(xié)程
resultChan <- &result{
err: err,
output: output,
}
}()
// Sleep 1s
time.Sleep(time.Second * 1)
// 取消上下文,取消子進(jìn)程,子進(jìn)程就會被干掉
cancelFunc()
// 從子協(xié)程中取出數(shù)據(jù)
res = <-resultChan
// 打印子協(xié)程中取出數(shù)據(jù)
fmt.Println(res.err)
fmt.Println(string(res.output))
}到此這篇關(guān)于golang代碼中調(diào)用Linux命令的文章就介紹到這了,更多相關(guān)golang調(diào)用Linux命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
golang中json小談之字符串轉(zhuǎn)浮點數(shù)的操作
這篇文章主要介紹了golang中json小談之字符串轉(zhuǎn)浮點數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03

