【问题标题】:How to destroy a golang sub process on Android?如何销毁Android上的golang子进程?
【发布时间】:2020-09-25 04:52:47
【问题描述】:

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

对于nodego 二进制文件,可从Termux 获得;

对于node子进程,可以在AndroidServicep.waitFor()中启动;到时候可以被p.destroy()杀死

但是对于go子进程,p.destroy()甚至p. destroyForcibly()可以启动但不能杀死;在这篇文章 https://medium.com/honestbee-tw-engineer/gracefully-shutdown-in-go-http-server-5f5e6b83da5a 中,它确保可以优雅地关闭 go 服务器,我尝试过,但 p.destroy() 仍然不起作用。

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

【问题讨论】:

    标签: android go subprocess kill-process


    【解决方案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 eventually
    if (p.isAlive()) {
        val klass = p.javaClass
        if (klass.getName().equals("java.lang.UNIXProcess")) {
            Log.d("AppDebug", "force terminate sub process ..")
            try {
                val f = klass.getDeclaredField("pid");
                f.setAccessible(true);
                val pid = f.getInt(p);
                // XXX: buggy here, if getInt throw an error, the filed is exposed!
                f.setAccessible(false);
                android.os.Process.killProcess(pid);
                Log.d("AppDebug", "force terminating done.")
            } catch (e: Exception) {
                Log.d("AppDebug", "force terminating failed.")
            }
        } else {
            Log.d("AppDebug", "force terminating not supported.")
        }
    }
    

    对不起,我的误导。目前我完全理解为什么在终止进程之前/之后添加一些关于ps -ef 的日志后我的 go 服务器无法被终止。

    其实我用go run main.go来启动服务器;但是,go run main.go 将编译代码并在 tmp 文件夹中生成二进制文件;然后它将产生一个子进程(执行二进制文件);当我执行p.destroy() 时,它只是杀死了go 进程,但子服务器进程仍然存在。

    正确的解决方案是,得到pid 像上面的代码;并使用ps -o pid= --ppid=<pid> 获取子树并杀死所有进程以进行清理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2010-09-08
      • 2012-12-31
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多