golang,再也不用管道了,exec.Command("bash", "-c", "ps -elf | grep xxx")

LiuYanYGZ發表於2024-03-13

摘自:https://www.jb51.net/article/249001.htm

func System_CmdCombinedOutput(cmd_line string) ([]byte, error) {
    mutex_exec.Lock()
    defer mutex_exec.Unlock()

    // old_handler := C.set_SIGCHLD_DFL()    // 自己實現, 用c語言儲存當前的訊號遮蔽字
    // defer C.set_SIGCHLD_old(old_handler)  // 自己實現, 用c語言恢復之前的訊號遮蔽字

    cmd := exec.Command("bash", "-c", cmd_line)
    output, err := cmd.CombinedOutput()

    return output, err
}

func System_CmdRun(cmd_line string) error {
    mutex_exec.Lock()
    defer mutex_exec.Unlock()

    // old_handler := C.set_SIGCHLD_DFL()    // 自己實現, 用c語言儲存當前的訊號遮蔽字
    // defer C.set_SIGCHLD_old(old_handler)  // 自己實現, 用c語言恢復之前的訊號遮蔽字

    cmd := exec.Command("bash", "-c", cmd_line)
    err := cmd.Run()

    return err
}

// main.go


func main() {

    output, err := System_CmdCombinedOutput("ps -elf | grep xxx")  
    fmt.Println(string(output))

    output, err := System_CmdRun("tcpdump -i any '((udp and (port 6886)) or (sctp))' -C 200 -Z root -z gzip -w /var/xx/lmt_dump_20240313095959.pcap")  
    fmt.Println(string(output))

}

相關文章