从 Bash 调用 Java 时无法执行二进制文件

Cannot execute binary file when calling Java from Bash

我正在使用 Ubuntu 14.04.

涉及4个文件:'compile.sh'、'execute.sh'、'work.c'、'tester.sh'.

在'compile.sh'中,它编译'work.c'文件并输出一个名为'execute.sh'的可执行文件。在我自己的测试过程中,我做 ./compile.sh,然后 ./execute.sh 到 运行 我的 C 程序。这行得通。

现在,'tester.sh' 是一个调用 Java 程序的脚本,而这个 Java 程序做同样的事情。它会先运行我的'compile.sh'然后执行'execute.sh'。它检查我的程序输出的正确性。 问题是,当我执行 ./tester.sh 时,出现以下错误

Reading first line from program...

./execute.sh: ./execute.sh: cannot execute binary file

First line of execution should match: Created \d heaps of sizes .+

Failed to execute (error executing ./execute.sh)

你可以忽略第三行“First line of execution....”;它会尝试检查我的输出是否与测试仪完全匹配。由于无法执行二进制文件,因此第一行肯定不匹配。 那么为什么它说“无法执行二进制文件”?

compile.sh

中的内容
#!/bin/bash
gcc -Wall work.c -o execute.sh 

tester.sh

中的内容
#!/bin/bash

java -cp bin/tester.jar edu.ssu.cs153.work1.Tester

(bin/tester.jar 在我的本地机器上;我们可以假设测试脚本没有任何问题。)

诊断

用 .sh 扩展名命名可执行文件很奇怪,但并非不允许。你的问题是 Java 代码试图 运行 它作为 shell 脚本(例如 bash ./execute.sh),它不是 shell 脚本所以它失败。您需要将 Java 更改为 运行 .sh 文件作为可执行文件而不是 shell 脚本。或者,更好(因为你可能无法修复 Java),修复编译,以便它生成具有不同名称的可执行文件(例如 work),并让 execute.sh 执行 ./work.

File execute.sh is just an output file from compiling the work.c file. It is just like a.out by default from gcc. I can run ./execute.sh from the terminal and see all the correct outputs.

麻烦的是,当你运行它时,你做了./execute.sh并且shell直接执行了。 Java 将其 运行 设置为 bash ./execute.sh,这会产生错误。在命令行试试。

处方

从表面上看,您需要更改 compile.sh,也许像这样(从 work.c 生成程序 work):

#!/bin/bash
gcc -o work -Wall work.c

然后您编写了一个名为 executable.sh 的 shell 脚本,内容为:

#!/bin/bash
exec ./work "$@"

此脚本 运行 将您的程序与给定的任何命令行参数一起使用。 exec 表示 shell 将自己替换为您的程序;这样做有一些小好处,但如果您从脚本中省略 exec 也没关系。