I’m getting a null pointer exception even if i already started the thread. Is there some other way to setcommands or pass arguments to a running thread?
public class MainClass{
public static void main(String [ ] args)
{
try{
GDBpipeWriter g = new GDBpipeWriter();
new Thread(g).start();
// Set commands
g.setcommand("run");
g.setcommand("list");
g.setcommand("list 10,20");
}catch(NullPointerException e){
}
}
}
public class GDBpipeWriter implements Runnable{
public volatile String command;
PrintWriter stdin;
public void setcommand(String com){
this.command = com;
stdin.println(command);
}
public void run(){
Process p = null;
try {
p = Runtime.getRuntime().exec("gdb a.out --interpreter=console");
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
stdin = new PrintWriter(p.getOutputStream());
stdin.flush();
stdin.println("break 4");
stdin.flush();
stdin.println("break 10");
stdin.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
Maybe a “race condition”, so stdin is not defined when you reach the first setcommand() call.
You call setcommand from main(), but stdin is not set already.
Update
You ask now how to do this. There are many ways to get that working. Here only one proposal:
Let setcommand() set the command member and nothing more. In the run() method put a while loop. in the while loop wait that command get set, send comand to the stream and reset command to null. Optional sleep() some ms, then continue the loop. HTH.