我正在尝试执行 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/