如何销毁Android上的golang子进程?

最近,我正在尝试使用 Android 子进程,Runtime.getRuntime().exec(command)发现我可以销毁 NodeJS http 服务器,但无法销毁 Go http 服务器。

对于nodego二进制,它可以从 Termux 获得;

对于node子进程,可以在Android中Service启动p.waitFor();时间到了,它可以被杀死p.destroy()

但是,对于 go sub 进程,它可以启动但不能被p.destroy()even杀死p. destroyForcibly();在本文https://medium.com/honestbee-tw-engineer/gracefully-shutdown-in-go-http-server-5f5e6b83da5a中,它确保可以正常关闭 go 服务器,我尝试过但p.destroy()仍然无法正常工作.

如果有人可以为我提供一种终止该过程的方法,我们将不胜感激。谢谢!


慕桂英4014372
浏览 126回答 1
1回答

偶然的你

刚刚想出了一个破解方法;不优雅;如果有的话,请指导我找到更好的解决方案!Log.d("AppDebug", p.javaClass.getName())// from above log// we can know Android use "java.lang.UNIXProcess" as implementation of java.lang.Process// to make sure the sub process is killed eventuallyif (p.isAlive()) {&nbsp; &nbsp; val klass = p.javaClass&nbsp; &nbsp; if (klass.getName().equals("java.lang.UNIXProcess")) {&nbsp; &nbsp; &nbsp; &nbsp; Log.d("AppDebug", "force terminate sub process ..")&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val f = klass.getDeclaredField("pid");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val pid = f.getInt(p);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // XXX: buggy here, if getInt throw an error, the filed is exposed!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f.setAccessible(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; android.os.Process.killProcess(pid);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("AppDebug", "force terminating done.")&nbsp; &nbsp; &nbsp; &nbsp; } catch (e: Exception) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.d("AppDebug", "force terminating failed.")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; Log.d("AppDebug", "force terminating not supported.")&nbsp; &nbsp; }}对不起我的误导。ps -ef目前我完全理解为什么在我添加一些关于杀死进程之前/之后的日志之后我的 go 服务器不能被杀死。实际上我go run main.go用来启动服务器;但是,go run main.go将编译代码并在 tmp 文件夹中生成二进制文件;然后它将产生一个子进程(执行二进制文件);当我这样做时p.destroy(),它只是杀死了该go进程,但子服务器进程仍然存在。正确的解决方案是,pid像上面的代码一样;并用于ps -o pid= --ppid=<pid>获取子树并杀死所有进程以进行清理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go