普通网友 2016-10-24 15:32
浏览 40
已采纳

无法查看exec.Command发出的OS级别的命令参数

My routine is supposed to spin 10 child processes from the same go executable binary (os.Args[0]), adding some command line arguments that are valid. All processes should live for a number of seconds, which is specified in one of the arguments.

func spinChildProcesses() {
    cmdParts := make([]string, 4)
    cmdParts[0] = "-c"
    cmdParts[1] = os.Args[0]
    cmdParts[2] = "--duration"
    cmdParts[3] = "10000"
    for i := 0; i < 10; i++ {
        proc := exec.Command("bash", cmdParts...)
        go proc.Start()
    }
}

func main() {
    # not showing code that parses duration arg
    # create 10 child subprocesses
    go spinChildProcesses()
    // set a duration to the process and terminate
    time.Sleep(time.Second * time.Duration(duration))
    fmt.Println(" - process terminating normaly")
}

When the above is run, looking at OS level I can see the arguments are not carried out. Only the root process has the arguments which I typed:

ps -ef | grep my-test-pr
root      3806 14446  0 15:23 pts/1    00:00:00 ./my-test-pr --duration 10000
root      3810  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3811  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3813  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3814  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3818  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3823  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3824  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3829  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3836  3806  0 15:23 pts/1    00:00:00 ./my-test-pr
root      3840  3806  0 15:23 pts/1    00:00:00 ./my-test-pr

Any idea why and how to ensure the arguments are passed to the children processes ?

  • 写回答

1条回答 默认 最新

  • douyue9704 2016-10-24 16:26
    关注

    The -c bash flag takes a single string argument to interpret. Since the argument to -c is only the string os.Args[0], that is all bash is executing, and the rest of the args are being ignored.

    To provide the arguments to your binary to be executed by bash -c, join them into a single string:

    var args []string
    args = append(args, os.Args[0])
    args = append(args, "--duration")
    args = append(args, "10000")
    for i := 0; i < 10; i++ {
        proc := exec.Command("/bin/bash", "-c", stringsJoin(args, " "))
        go proc.Start()
    }
    

    Or simply exec your binary directly without the extra shell.

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

报告相同问题?

悬赏问题

  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序