golang exec.Command无法运行C二进制文件。

huangapple go评论86阅读模式
英文:

golang exec.Command couldn't run C binaries

问题

我正在使用exec.Command和exec.Start()执行一个C可执行文件。我的C可执行文件位于当前目录,以下是我的代码:

cmd := exec.Command("./a.out")
// stdout,err := cmd.StderrPipe()
stderr,_ := cmd.StderrPipe()

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

log.Printf("Waiting for command to finish...")
s,err := ioutil.ReadAll(stderr)
log.Printf(string(s))
err = cmd.Wait()
log.Printf("Command finished with error: %v", err)

当我运行这段代码时,我得到的输出是:

2014/12/10 07:49:39 Waiting for command to finish...
2014/12/10 07:49:39 Command finished with error: exit status 11

我的C hello world程序如下:

#include <stdio.h>
int main(){
    printf("hello world");
}

C代码是使用gcc版本4.8.2编译的,可执行文件名为a.out。

C可执行文件a.out是一个简单的hello world程序,我得到了正确的输出,但我不明白为什么exec.Wait()以状态码11而不是0退出。

当我在Linux终端上运行时,可执行文件('a.out')正常运行,没有任何故障或错误。

英文:

I executing a C executable using exec.Command and exec.Start(). My C executable is in the current directory and this is my code

cmd := exec.Command(&quot;./a.out&quot;)
// stdout,err := cmd.StderrPipe()
stderr,_ := cmd.StderrPipe()

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

log.Printf(&quot;Waiting for command to finish...&quot;)
s,err := ioutil.ReadAll(stderr)
log.Printf(string(s))
err = cmd.Wait()
log.Printf(&quot;Command finished with error: %v&quot;, err)

When i run this code, this is the output i get

2014/12/10 07:49:39 Waiting for command to finish...
2014/12/10 07:49:39 Command finished with error: exit status 11

My C hello world program is

#include &lt;stdio.h&gt;
int main(){
printf(&quot;hello world&quot;);
}

The C code is compiled with gcc version 4.8.2 and executable is a.out.

The C executable a.out is a simple hello world program, i am getting the correct output, but i can't understand why exec.Wait() is exiting with status code 11 and not with 0.

The executable('a.out') is running normally when i run on a linux terminal without any faults or errors

答案1

得分: 4

我从GitHub上得到了答案这里

它返回11是因为输出的长度是11,并且在我的Hello World程序中没有返回语句。所以当程序结束时,main函数从AX寄存器返回。

英文:

I got the answer from github here

It is returning 11 because the output length is 11 and there is no return statement in my hello world program. So main returns from AX register when it ended.

huangapple
  • 本文由 发表于 2014年12月10日 16:25:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/27396282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定