1

The issue is i want to kill a process only if its running, otherwise i want to do something else.

This is my code right now (sublime as an example):

try {
    Process p = Runtime.getRuntime().exec("pidof sublime_text");

    if (p != null){
        Runtime.getRuntime().exec("pkill -f sublime");
    }
}
catch (Exception e) {
    System.out.println(e.getMessage());
}

Runtime.getRuntime().exec("pidof sublime_text"); ALWAYS returns a process, even if this one doesn't exist, i mean, i can execute: Runtime.getRuntime().exec("pidof nonExistingProcess"); and this will still return a process without error, and then the kill "pkill" command Runtime.getRuntime().exec("pkill -f nonExistingProcess"); doesn't throw an Exception either, what can i do?

2

2 Answers 2

1

You're starting the processes but are not reading their output or return status (or even waiting for them to complete), so your code doesn't actually react in any way to the processes you start.

You might be used to system in PHP or similar systems where that call only returns once the executed command is complete. Runtime.exec() is different in that you start the process but it's up to you to read it's output from the Process that gets returned.

So p doesn't actually represent sublime, but it's the process executing pidof and you must read its output to get to the information you want.

Sign up to request clarification or add additional context in comments.

Comments

0

Of course there's a process; 'pidof someRandomGarbage' is still an application that runs. The fact that the application, if run, returns 'nope', doesn't magically make the process disappear. You have to use the methods of the Process class to determine what the result of running pidof someRandomGarbage does. p.exitValue() is probably what you're looking for. To determine the actual output you'd have to use p.getInputStream().

Note that using relative paths is a very bad idea; it means you're reliant on the PATH variable and on java parsing it properly. Try /usr/bin/pkill, or something configurable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.