如何执行命令行

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.

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.