1

我试图在 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();

第二次执行 out.writeBytes(); ,我得到一个java IOException:“错误的文件号”。我的应用程序必须执行多个本机程序,但始终使用相同的进程。任何人都知道为什么这不起作用?

4

2 回答 2

1

请注意,shell 不是公共 SDK 的一部分(请注意,SDK 文档中的任何地方都没有记录它),因此此代码实际上依赖于私有 API。

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. :)

于 2010-08-28T20:23:38.857 回答
0

当你调用时out.close(),它会自动调用close()你进程的输出。

每次调用时,p.getOutputStream()您都会得到相同的OutputStream结果,在您第二次使用 out 时,p.getOutputStream()返回一个已经关闭的OutputStream

基本上使用您的代码,您实际上并不需要关闭第一个DataOutputStream.

资料来源:

于 2010-08-28T14:12:21.193 回答