I am working on an assignment where I have to implement a basic CPU and memory module using Process as "fork" and InputStream/OutputStream as the "pipes". I am having trouble getting the basic communication back and forth working correctly.
My code for CPU is:
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();
}
}
And my code for Memory.java is:
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];
}
My input file has the following text:
1
2
3
If I just run Memory.java it works just fine with reading "READU", then an address, then it prints out the value at that address in the memory array. However, when I run CPU, I get java.util.NoSuchElementException: No line found
from the String temp = fromMem.nextLine();
line in CPU.
Hopefully my question is clear. I have taken out any code that doesn't affect this problem I am having. Please let me know if you need to see any other code.
Thank you.