public void close() {
      boolean idle = isIdle(); // idle must be checked synchronized

      synchronized (this) {
        if (!running)
          return;
        running = false;
        closed = true;
      }

      // This method should not be called from the main thread unless the shell is idle and can be cleaned up with
      // (minimal) waiting.

      if (!idle)
        waitForIdle();

      try {
        try {
          stdin.write(("exit\n").getBytes("UTF-8"));
          stdin.flush();
        } catch (IOException e) {
          //noinspection StatementWithEmptyBody
          if (e.getMessage().contains("EPIPE") || e.getMessage().contains("Stream closed")) {
            // we're not running a shell, the shell closed stdin,
            // the script already contained the exit command, etc.
          } else {
            throw e;
          }
        }

        // wait for our process to finish, while we gobble away in the background
        process.waitFor();

        // make sure our threads are done gobbling, our streams are closed, and the process is
        // destroyed - while the latter two shouldn't be needed in theory, and may even produce
        // warnings, in "normal" Java they are required for guaranteed cleanup of resources, so
        // lets be safe and do this on Android as well
        try {
          stdin.close();
        } catch (IOException e) {
          // stdin going missing is no reason to abort
        }
        stdout.join();
        stderr.join();
        stopWatchdog();
        process.destroy();
      } catch (InterruptedException | IOException e) {
        // various unforseen IO errors may still occur
      }
    }
Close shell and clean up all resources. Call this when you are done with the shell. If the shell is not idle
(all commands completed) you should not call this method from the main UI thread because it may block for a
long time. This method will intentionally crash your app (if in debug mode) if you try to do this anyway.
imitate/src/main/java/com/engineer/imitate/shell/Shell.java