dongpo0409 2019-03-18 13:50
浏览 31
已采纳

如何执行命令行

I am trying to execute two commands:

  • sudo ip link set can0 type can bitrate 500000
  • sudo ip link set can type can restart-ms 1000

here is my code:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main(/*in string*/)/*(out bool)*/ {

        in :="setup"

    switch in {

    case "setup":
        bringUp()
        setRestart()
        log.Println("can0 is brought up")
        //return true

    case "restart":
        setRestart()
        log.Println("can0 is restarted")
        //return true

    default:
        log.Println("System cannot be brought up, contact administrator")
        //return false
    }
}


func bringUp (){
    cmd := exec.Command("sh", "-c", "sudo ip link set can0 type can bitrate 500000")

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}

func setRestart(){
    cmd:= exec.Command("sh", "-c", "sudo ip link set can type can restart-ms 10000")

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    err := cmd.Run()

    if err != nil{
        log.Fatal(err)
    }
}

Whenever I execute it goes in to "setup" case and starts executing the bringUp function but it can never finish executing and I can't understand why. I am working on a raspberry pi.

  • 写回答

1条回答 默认 最新

  • dqd22496 2019-03-18 14:20
    关注

    Your go code looks correct. The problem lies with sudo, I believe. I replaced your commands with benign commands like sudo touch /tmp/bringUp-executed etc. The code did prompted for my sudo password - but once inputed - completed without issue.

    Are you running your go-executable in a headless fashion? And thus has no access to the console for password input? I would suggest creating wrapper scripts for your any root-level tasks and give them password-less sudoer privileges as outlined here.

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

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏