go - 执行外部命令并返回其输出

标签 go

我正在尝试执行 linux 命令并将输出转换为 int。这是我当前的代码:

package main

import (
    "os/exec"
    "os"
    "strconv"
    _"fmt"
    "log"
    "bytes"
)

func main(){

    cmd := exec.Command("ulimit", "-n")
    cmdOutput := &bytes.Buffer{}
    cmd.Stdout = cmdOutput
    err := cmd.Run()
    if err != nil {
      os.Stderr.WriteString(err.Error())
    }

    count, err := strconv.Atoi( string(cmdOutput.Bytes()) )
    if err != nil {
        log.Fatal(err)
    }

    if count <= 1024 {
        log.Fatal("This machine is not good for working!!!")
    }
}

这是我当前的错误:

2018/10/12 14:37:27 exec: "ulimit -n": executable file not found in $PATH

我不明白此错误的含义以及如何修复它。

最佳答案

linux 中没有可以运行的ulimit 程序。

ulimit 是 shell 的内置函数。因此,您需要运行一个 shell 并让 shell 运行其内部的 ulimit 命令。

cmd := exec.Command("/bin/sh", "-c" "ulimit -n")

您还必须从 ulimit 命令的输出中删除换行符,例如

count, err := strconv.Atoi( strings.Trim(string(cmdOutput.Bytes()),"\n"))

更好的选择是通过 go 中的系统调用 API 检索这些限制,请参阅 How to set ulimit -n from a golang program? - 接受的答案首先获取并打印当前限制。

关于go - 执行外部命令并返回其输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52779140/

相关文章:

algorithm - 为什么代码在 Codility 测试用例中返回负值?

go - 在任何事情之前制作 map

string - 使用字符串作为函数名 - golang

macros - Go:用于编写测试代码的类似 C 的宏

reference - 另一种类型中自定义类型的 Golang slice 作为引用

reactjs - Go Api 返回 Unauthorized

arrays - 如何增加数组大小

google-app-engine - 无法使用golang从数据存储中获取基于结构值的记录

戈朗。仅从包中导入一个文件

go - 实现阅读器接口(interface)