javajsch

Remote process stops as soon as my Java app exits


I'm running a remote process (that runs on remote Debian machine within its Terminal via "./st.cmd" command below) through my Java app which I want to keep running throughout the lifespan of my app as well as after this app exits, unless some remote user terminates it or a local user terminates it using an icon inside my app. Right now, it also terminates when my Java app exits. [I think this happens because the object "shellChannel" gets destroyed upon app exit] Following is the code:

public static void runProcess() {
    RemotePC pc = (RemotePC)MainWindow.getInstance().selectedJTreeNode.getUserObject();
    
    try {
        if (connectedShellChannel(pc)) { // returns true upon successful connection
            PrintStream shellStream = new PrintStream(pc.shellChannel.getOutputStream(), true);
            // where shellChannel is com.jcraft.jsch.Channel object created elsewhere
            shellStream.println("./st.cmd");

            shellStream.flush();
            shellStream.close();

            Prompt.ShowInfo("Specified process is now running successfully \n on selected PC (IP: " + pc.IP + ")", "Message from Remote PC", Global.SuccessIcon);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Prompt.ShowError("A secure communication channel could not be established \n with the Remote PC.\n\nSpecified process could not be run.", "Secure Communication not established");
    }
}

Any suggestions??


Solution

  • Is this what you want to do:

    1. Java programs starts up
    2. Java program opens up an SSH channel to a remote SSH server; a shell on that machine is started
    3. Java program sends a command to start a process on that remote machine within the shell
    4. Java program exits
    5. terminating the java program, hangs up the channel/SSH connection, in turn that will shutdown the process you started in (3)

    But you want the remote process to continue?

    Then what you need to do is in step (3) to cause the shell to spawn or fork the process into the Background, then when you terminate the connection (5), the remote process will already be running asynchronously on the remote machine so it won't be shutdown when you sever the connection.

    So this is not a Java matter, but a Unix Shell question.

    Depending on your shell, all you might need to do is put an & at the end of the program/script invocation.

    So suppose you were starting a very long running process to zip up some files:

    zip -r new.zip stuffToZip/*
    

    then on most shells to get that zip process to fork into the background, (so that it would continue if you exited you shell), you'd type:

    zip -r new.zip stuffToZip/* &
    

    Ref: https://linuxize.com/post/how-to-run-linux-commands-in-background/