im trying to do this on Android:
Process p = Runtime.getRuntime().exec("sh");
DataOutputStream out = new DataOutputStream(p.getOutputStream());
out.writeBytes("something useful\n");
out.close();
p.waitFor();
out = new DataOutputStream(p.getOutputStream());
out.writeBytes("something useful\n");
out.close();
p.waitFor();
The second time I execute out.writeBytes(); , I get a java IOException: “Bad file number”.
My app has to execute several native programs, but always use the same process.
Anyone know why this does not work?
Note that the shell is not part of the public SDK (note it is not documented anywhere in the SDK documentation), so this code is in effect relying on private APIs.
Also this puts you outside of the normal application model — we have no guarantee what will happen to a process you have forked and is not being managed by the platform. It may get killed at any time.
This is also a very inefficient way to do things, compared to doing whatever the command is doing in your own process. And starting a separate process for a command won’t let it do anything more than you can, because it still runs as your uid.
So basically… for 99.99% of apps please don’t do this. If you are writing a terminal app… well, okay, only geeks are going to care about that anyway, and it isn’t going to be of much use since it runs as your uid, but okay. But otherwise, please no. 🙂