通过 Runtime.getRuntime().exec(“su”); 将 Control-C 发送到正在运行的进程;
我正在开发一个需要以 root 用户身份运行命令的应用程序,因此我使用:
process = Runtime.getRuntime().exec("su");
然后我启动进程:
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("tcpdump\n");
当我需要进程完成时 os.writeBytes("exit\n");
不起作用,并且 process.waitFor();
get 被阻止并且进程无法完成。我需要向进程发送 Control-C 来停止它,但我不知道该怎么做。
谢谢。
I'm developping an app which needs to run a command as root user so I use:
process = Runtime.getRuntime().exec("su");
Then I launch te process with:
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("tcpdump\n");
When I need the process to finish os.writeBytes("exit\n");
doesn't work and process.waitFor();
get's blocked and the process doesn't finish. I need to send Control-C to the process to stop it but I don't know how I could do it.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查明 API 的某处是否有kill() 方法,并使用该方法向目标进程发送SIGINT 信号。
Find out whether the API has a kill() method somewhere and use that method to send the SIGINT signal to the target process.
在他的 github 上,Chainfire 提供了一个
的示例实现
Shell
类,您可以使用该类以 root 身份执行命令。该类使用Threads
处理所有任务,因此您可以确保该命令即使不返回也不会阻塞。代码片段:
或者,如果您确定
su
二进制文件可用,您可以只运行命令(注释行)并跳过检查。资料来源:SU 操作方法
On his github, Chainfire provides a sample implementation of a
Shell
class that you can use to execute commands as root. The class handles all the tasks usingThreads
so you can be sure that the command will not block even if it does not return.Code Snippet:
Or if you are certain that the
su
binary is available, you can just run your commands (commented line) and skip the check.Source: How-To SU
将其添加到您想要发出 ctrl-c 信号的位置。
如果有多个以 tcpdump 名称运行的进程,并且需要有选择性,请使用 pidof 和 grep 命令找出具体的进程 id。如果答案对您有用,请接受答案。如果您遇到问题,请在评论中告诉我。
Add this at the location you want a ctrl-c signal to be issued.
If there are multiple processes running by the name of tcpdump and you need to be selective, find out the specific process id using pidof and grep commands. Accept the answer if it worked for you. Let me know in comments if you are facing issues.