我创建了一个服务器程序,当它接收到一些命令时,执行一些操作。
当它接收到命令“android”(当客户端从android设备连接时会发生这种情况)时,我希望我的服务器启动shell脚本,当客户端断开连接时,我希望它停止此脚本的执行。
此外,当web浏览器客户端连接并发送命令“browser”时,服务器将启动另一个脚本。
这两个脚本不能同时使用,因为它们使用相同的资源。这就是为什么当客户机断开连接时我需要停止它们(我知道我不能让这两种客户机同时连接)。
目前,我已经能够启动脚本,但无法阻止它们。以下是服务器中我的run方法的代码:

@Override
public void run() {
    try {
        BufferedReader ins = new BufferedReader(new InputStreamReader(soc.getInputStream()));

        Runtime r = Runtime.getRuntime();
        Process p = null;

        int i = 0;
        while (i < 1) {
            String request = ins.readLine();
            if (request == null || request.equals("close")) {
                p.destroy();
                System.out.println("The child was destroyed? "+p.exitValue());
                i++;
            }
            else {
                if (request.equals("android")) {
                    p = r.exec("sh /home/pi/test-raspicamsrc.sh &");
                }
                else if (request.equals("browser")) {
                    p = r.exec("sh /home/pi/test-http-launch.sh &");
                }
                else if (request.equals("left")) {
                    serialPort.writeBytes("4".getBytes());//Write data to port
                }
                else if (request.equals("right")) {
                    serialPort.writeBytes("6".getBytes());
                }
                else if (request.equals("stop")) {
                    serialPort.writeBytes("5".getBytes());
                }
                else if (request.equals("forward")) {
                    serialPort.writeBytes("8".getBytes());
                }
                else if (request.equals("backward")) {
                    serialPort.writeBytes("2".getBytes());
                }
                else {
                    System.out.println("Unknown command");
                }
            }
        }
        ins.close();
        soc.close();
        // We always stop the car in the end.
        serialPort.writeBytes("5".getBytes());
    }

第一次断开android设备的连接时,p.exitValue()的输出为143,脚本继续执行。之后,如果我再连接一次android客户端,它似乎不会再次启动脚本(这是一件好事,我不知道为什么或者也许它确实启动了脚本,但由于资源已经在使用中,它会很快关闭),当我断开这个新客户端的连接时,它会返回p.exitValue()。这是一个正常的事情,因为这个过程不存在。但在这段时间内,第一个脚本的启动过程一直在运行。
我想知道为什么我的命令0没有终止我的脚本进程。我认为这可能是因为它停止了sh进程,而不是我的脚本进程(两个不同的进程)有点像这里java Process stop entire process tree
希望有办法解决这个问题,谢谢!:)

最佳答案

可以通过以下命令检查脚本是否在服务器中运行。
PS-EFW GREP“流程名称”
现在要停止Java程序中的脚本,可以执行以下命令。
pkill-9-f“测试raspicamsrc.sh”
pkill命令通过提供进程模式来终止进程。如果您想在没有pid的情况下杀死firefox应用程序,您可以如下执行。
pkill-9-f“火狐”

10-08 08:09