Damian
Damian

Reputation: 789

Run BASH command in JAVA in background

I made a function that executes a command from BASH, and i want to make it run in background and never stop the execution of the main program.

I could use screen -AmdS screen_thread123 php script.php but the main ideea is that i learn and understand how threads work.

I have a basic knowledge about this, but right now i want to create a quick dynamic thread like the example of bellow :

public static void exec_command_background(String command) throws IOException, InterruptedException
{

    List<String> listCommands = new ArrayList<String>();
    String[] arrayExplodedCommands = command.split(" ");

    // it should work also with listCommands.addAll(Arrays.asList(arrayExplodedCommands));
    for(String element : arrayExplodedCommands)
    {
        listCommands.add(element);
    }

    new Thread(new Runnable(){
        public void run()
        {
            try
            {
                ProcessBuilder ps = new ProcessBuilder(listCommands);

                ps.redirectErrorStream(true);
                Process p = ps.start();

                p.waitFor();
            }
            catch (IOException e)
            {
            }
            finally
            {
            }
        }
    }).start();
}

and it gives me this error

NologinScanner.java:206: error: local variable listCommands is accessed from within inner class; needs to be declared final
ProcessBuilder ps = new ProcessBuilder(listCommands);
1 error     

Why is that and how can i solve it? I mean how can i access the variable listCommands from this block?

new Thread(new Runnable(){
        public void run()
        {
            try
            {
                // code here
            }
            catch (IOException e)
            {
            }
            finally
            {
            }
        }
    }).start();
}

Thanks.

Upvotes: 2

Views: 2069

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201409

You don't need that inner class (and you don't want to waitFor)... just use

for(String element : arrayExplodedCommands)
{
    listCommands.add(element);
}
ProcessBuilder ps = new ProcessBuilder(listCommands);

ps.redirectErrorStream(true);
Process p = ps.start();
// That's it.

As for your question of accessing the variable listCommands in your original block; make the reference final - like so

final List<String> listCommands = new ArrayList<String>();

Upvotes: 1

Related Questions