drgaeqdqiiyg14608 2018-12-11 15:20
浏览 165

如何使用exec和syscall软件包golang传递端口值以启动服务器

We are trying to implement a program in go which runs another go program from the specified path like

path, _ := exec.LookPath("program-name")

Next we have given a set of go commands to run the go program like

args := []string{"go", "install", "&&", "-port", "18000"}

We passed both path and args along with os.Environ() to the syscall.Exec(). In order to run the project which we are calling has a check which tells us -port is required. As -port is not an executable command so it not taking the port value.

The requirement is when we type go install && project-name -port 19000 the program should run.

The query is there any way to achieve this and how can we pass the port value to get the desired outcome.

  • 写回答

1条回答 默认 最新

  • doulianxi0587 2018-12-11 16:19
    关注

    This does not work for two reasons

    args := []string{"go", "install", "&&", "-port", "18000"}
    

    First, "project-name" is missing. I assume this is a simple typo.

    Second, syscall Exec does not use a shell to launch commands. The && construct and running multiple commands from one line are shell features

    To make syscall Exec do this you could call it, check the return value and then call it again with the second command

    Or you could use syscall Exec to launch a shell. Below there is an example of launching a shell - (with os/exec, but this is very similar in this case) to run two commands with a &&

    package main
    
    import (
        "fmt"
        "os/exec"
    )
    
    func main() {
        args := []string{"-c", "touch a && ls -l"}
        cmd := exec.Command("bash", args...)
        stuff, err := cmd.Output()
        fmt.Printf("Command finished with error: %v", err)
        fmt.Printf("%s", string(stuff))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!