dsvcqvp139098 2018-10-12 12:02
浏览 39
已采纳

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

I'm trying to execute a linux command and convert the output to an int. This is my current code:

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!!!")
    }
}

This is my current error:

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

I don't understand what this error means and how I can fix it.

  • 写回答

1条回答 默认 最新

  • dongpao1873 2018-10-12 12:12
    关注

    There is no ulimit program in linux that you can run.

    ulimit is a builtin of a shell. So you need to run a shell and have the shell run its internal ulimit command.

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

    you will also have to remove the newline from the output of the ulimit command, e.g.

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

    A better alternative is to retreive these limits via the syscall API in go, see How to set ulimit -n from a golang program? - the accepted answer first gets and prints the current limit.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 MIT控制器能控制不稳定系统吗
  • ¥15 公司代码X对业务伙伴X无效,处理方法?
  • ¥15 微信内链接跳转到浏览器打开怎么实现
  • ¥15 三角波可以直接加施密特电路整形到矩形波吗实物
  • ¥15 html,php,在使用html请求php文件时发生了错误,无法请求到php文件读取数据库并用javascript进行数据显示,刷新
  • ¥15 touchsocket udp组播
  • ¥20 MAC怎么安装Silverlight 插件?以及安装了怎么启用
  • ¥15 VS2012中查询语句无法填入解析,数值传不进去
  • ¥15 gis系统开发出现命名空间“ESRI.ArcGIS”中不存在类型或命名空间名“Analyst3D”报错
  • ¥15 怎么让ai定时给我发信息 c#或者python