drb0901500211 2017-07-28 17:44
浏览 33
已采纳

如何将控制台输入从Golang传递到子流程

I have the following C program.

#include<stdio.h>


int main() {
    int i = 0;
    char ch;

    printf("Starting test application
");

    for (i=0; i<10; i++) {
        ch = getchar();

        printf("character at %d = %d
", i, ch);
    }

    return 0;
}

I want to run this program as a sub-process from Go language. In my Go code, I have a byte array which I want to be used as input to my C program. I tried following approach and it did not work.

cmd := exec.Command("/home/dodtech/go-workspace/MachineListener/Test")

cmd.Stdout = os.Stdout
err := cmd.Start()

if err == nil {
    var ctrlc [9]byte
    ctrlc[0] = 0x00
    ctrlc[1] = 0x01
    ctrlc[2] = 0x02
    ctrlc[3] = 0x03
    ctrlc[4] = 0x04
    ctrlc[5] = 0x05
    ctrlc[6] = 0x06
    ctrlc[7] = 0x07
    ctrlc[8] = 0x08
    ctrlc[9] = 0x09

    cmd.Stdin = bytes.NewReader(ctrlc[0:])
    cmd.Stdin.Read(ctrlc[0:])
}

To be noted, both of the above program is just a test program and they only represent what I want to achieve. They are not meant to be efficient and was not written according to programming guidelines(for example the way byte array was created). If I can solve my problem for this small case, I will be able to port it to my actual software code. I would appreciate if anyone can guide me how I can do this .

  • 写回答

2条回答 默认 最新

  • duanpeng1532 2017-07-28 17:55
    关注

    If you want to write to the sub-process standard input, you should use StdinPipe.

    Like:

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "Hello World")
    

    See the docs for a complete example:

    https://golang.org/pkg/os/exec/#Cmd.StdinPipe

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?