阶段一:使用Java调用我们在Linux上面的shell脚本实现对C语言的编译链接运行
本章节的内容完全在Linux环境中实现
1.编写C语言测试代码 demo.c
#include<stdio.h>
int main(){
printf("hello linux\n");
return 0;
}
2.编写shell脚本对C语言代码进行 编译 运行 run.shell
#!bin/bash
gcc demo.c -o demo.out # 编译
./demo.out # 运行代码
rm demo.out #运行完之后直接删除.out文件
3.编写Java代码进行测试
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestShell {
public static void main(String[] args) {
Process process;
try {
process = Runtime.getRuntime().exec("bash ./run.shell");//运行我的shell脚本
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int exitValue = process.waitFor();
while((line = reader.readLine())!= null){
System.out.println(line);
}
if (exitValue == 0){
System.out.println( "successfully executed the linux command");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
编译Java代码
javac TestShell.java
运行Java代码
java TestShell
1605106997355.png
注意:
错误1:在运行代码的时候直接 Java 文件名 不要点class
1605105976811.png
错误2:文件名要和类名同名,不然会有如下错误
1605105997013.png