0

I dont know why, but I can only execute a very small pallet of commands on my Raspberry 3B from code (I cane even execute echo). For some reason, 99% of the commands that you would normally be able to do in the terminal itself, you cant do from code.

Example: I execute this java code: Runtime.getRuntime().exec("echo hi");

And I get this: `java.io.IOException: Cannot run program "echo hi": error=2, No such file or directory

Is there a PATH configuration that I dont have access to in java code? why cant I execute any commands to the raspberry pi from code?

9
  • 2
    echo is a shell builtin. So the command should really be/bin/bash -c "echo hi". I would use an array for commands and be ready to read stdin and stderr, preferably in dedicated threads Commented Sep 27, 2021 at 22:50
  • Try asking your ide for the javadoc for the exec you are using. It probably expects an array of words, not a command string. Commented Sep 27, 2021 at 22:52
  • @g00se - Although echo is a shell builtin, there is also a /bin/echo (including on a random Raspberry Pi Zero I just looked at). Commented Sep 27, 2021 at 22:59
  • If that's present, it might not be in $PATH. Clearly isn't as the command is not recognised Commented Sep 27, 2021 at 23:05
  • I just wrote a quick Java test on my Pi (which has the stock Raspbian non-GUI image). Works for me in the sense that I get no exception and the process exits with 0. No echo output seen though. Commented Sep 27, 2021 at 23:10

1 Answer 1

1

I've written some example that uses the exec() call. There are other methods to start processes from within Java (ProcessBuilder is the keyword here), but this example is relatively easy to understand:

import java.util.*;
import java.io.*;
import java.text.*;

public class X {

    public static void main(String argv[])
    {
        String args[] = { "/bin/bash", "-c", "uptime" };
        try {
            Process p = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = in.readLine();
            while (line != null) {
                System.out.println("Found: " + line);
                line = in.readLine();
            }
        } catch (Exception e) {
            System.err.println("Some error occured : " + e.toString());
        }
    }

}

Basically the program executes the command line /bin/bash -c uptime; just an uptime would have done the same, but I wanted to show how to work with command line arguments for the program to start.

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

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.