Java - (android) 刷新 OutputStream 后重用进程
我试图在 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:“文件号错误”。 我的应用程序必须执行多个本机程序,但始终使用相同的进程。 有人知道为什么这不起作用吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,shell 不是公共 SDK 的一部分(请注意,SDK 文档中没有记录它),因此此代码实际上依赖于私有 API。
此外,这使您脱离了正常的应用程序模型——我们无法保证您分叉且不受平台管理的进程会发生什么。随时都有可能被杀死。
与在您自己的进程中执行命令所做的任何操作相比,这也是一种非常低效的执行方式。为一个命令启动一个单独的进程不会让它做任何你能做的事情,因为它仍然作为你的 uid 运行。
所以基本上...对于 99.99% 的应用程序请不要这样做。如果您正在编写一个终端应用程序...好吧,好吧,无论如何,只有极客才会关心这一点,而且它不会有多大用处,因为它作为您的 uid 运行,但是好吧。但除此之外,请不要。 :)
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. :)
当您调用
out 时。 close()
,它会自动在进程的输出流上调用close()
。每次调用
p .getOutputStream()
在第二次使用 out 时,您会得到相同的OutputStream
,p.getOutputStream()
返回一个已经关闭的OutputStream.
基本上,对于您的代码,您实际上不需要关闭第一个
DataOutputStream
。来源:
来源DataOutputStream
扩展FilterOutputStream
FilterOutputStream.close()的来源
When you call
out.close()
, it will automatically callclose()
on the ouputstream of your process.Each time you call
p.getOutputStream()
you get the sameOutputStream
, on your second use of out,p.getOutputStream()
returns an already closedOutputStream
.Basically with your code, you don't really need to close the first
DataOutputStream
.Sources :
DataOutputStream
extends FilterOutputStream
FilterOutputStream.close()