我正在做一个作业,其中我必须实现一个基本的CPU和内存模块,使用Process作为“ fork”,而InputStream / OutputStream作为“ pipes”。我在使基本通信来回正常工作方面遇到麻烦。
我对CPU的代码是:
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("java Memory.java " + "testInput.txt");
InputStream is = proc.getInputStream();
OutputStream os = proc.getOutputStream();
Scanner fromMem = new Scanner(is);
PrintWriter toMem = new PrintWriter(os);
//Now the main loop
IR = 0;
PC = 0;
while(IR != 50){ //END command
System.out.println("PC: " + PC);
//Get the next instruction
toMem.println("READU");
toMem.println(PC);
toMem.flush();
String temp = fromMem.nextLine();
System.out.println(temp);
PC++;
}
}catch (Throwable t){
t.printStackTrace();
}
}
我对Memory.java的代码是:
static int[] mem = new int[2000];
public static void main(String[] args) {
initMemory(args[0]); //Fills the mem array with values from input file
Scanner fromCPU = new Scanner(System.in);
String input = "";
while(input != "END"){
int toSend;
input = fromCPU.nextLine();
switch (input){
case "READU": toSend = read(Integer.parseInt(fromCPU.nextLine()),true); //returns value at given address in memory
System.out.println(toSend); //Send the value returned from memory
break;
default: break;
}
}
}
static int read(int address,Boolean userMode){
if(userMode && address > 999){
System.out.println("Memory Violation. Accessing system address " + address + " in user mode.");
return -999999999;
}
return mem[address];
}
我的输入文件包含以下文本:
1
2
3
如果我只运行Memory.java,则可以通过读取“ READU”(一个地址)正常工作,然后在内存阵列中的该地址打印出该值。但是,当我运行CPU时,我从CPU的java.util.NoSuchElementException: No line found
行中获得了String temp = fromMem.nextLine();
。
希望我的问题很清楚。我已取出任何不会影响我遇到的问题的代码。如果您需要查看其他任何代码,请告诉我。
谢谢。