階段一:使用Java調(diào)用我們?cè)贚inux上面的shell腳本實(shí)現(xiàn)對(duì)C語言的編譯鏈接運(yùn)行
本章節(jié)的內(nèi)容完全在Linux環(huán)境中實(shí)現(xiàn)
1.編寫C語言測(cè)試代碼 demo.c
#include<stdio.h>
int main(){
printf("hello linux\n");
return 0;
}
2.編寫shell腳本對(duì)C語言代碼進(jìn)行 編譯 運(yùn)行 run.shell
#!bin/bash
gcc demo.c -o demo.out # 編譯
./demo.out # 運(yùn)行代碼
rm demo.out #運(yùn)行完之后直接刪除.out文件
3.編寫Java代碼進(jìn)行測(cè)試
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");//運(yùn)行我的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
運(yùn)行Java代碼
java TestShell