So essentially, I am trying to run the command "/dir/command -arg" to change the LED color on a USB device in Java. I am using Ubuntu 10.04. When I run the command from the terminal, it works just fine.
However, I tried every iteration of Runtime.exec() that I could find and none of them seem to work. I then created a script with the following contents:
#!/bin/bash
echo "hello"
/dir/command -arg
when I run this from a terminal it works just fine. However when I run
#Override
public void run() {
String[] lookupCmd = {"/bin/sh","-c", "sh /dir/script.sh"};
try {
Runtime runtime = Runtime.getRuntime();
Process lookupProc = runtime.exec(lookupCmd);
lookupProc.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(lookupProc.getInputStream()));
String line = reader.readLine();
while (line != null) {
id.add(line);
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e) {
System.err.println(e);
}
}
"hello" print but nothing else. There is no error.
My other command should not yield any output, but simply change the color of an LED. However when I run it with the same command but a different arg which yields an ouput, it still only prints "hello".
I also made sure that my user has permissions to the /dev folder with the usb device.
I wasn't running the error stream, so I've added that.
After that I realized I was missing an environment variable, so added:
String[] envar = {"VAR=path"}
and called:
runtime.exec(lookupCmd, envar);
Works great now.
Related
I've been trying to make an app to act as a ssh / scp client to make transferring files easier from my laptop to my desktop and currently I have been able to get the output of a ls command and get the file tree for the host and remote user, however this requires input in the terminal I am running the app with.
Is it possible to be able to embed a terminal window into a gui as I have went about making an interpreter however things like tab completion and running, for example, python3 don't work. I am also hoping to have full use of a terminal and be able to run commands like vim rather than just print the output of commands which is what I currently have.
My code for executing the commands is:
public void processCmd(String command) {
if (command.equals("exit")) {
System.exit(0);
} else if (command != null && !command.isEmpty()) {
execCommand(command);
}
}
public void execCommand(String input) {
String result = null;
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(input);
BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
result += inputLine;
}
in.close();
} catch (IOException e) {
System.out.println("Error");
}
}
The main problem is that when anything like python or vim is run, the app will hang and not do anything, python won't even show up in terminal, however, if I run vim, it will change the terminal screen (not in the app) to mostly vim but without the bottom bar.
I have a code which calls a specific command within the Mac Terminal, I then use a buffered reader to read and print the result from the terminal. I have been doing this with a couple of commands, only problem is I am now in need of using the command ps -ef | grep google (program name is of course different, but for now I'll just use google). The only issue by using this command is the fact that the buffered reader doesn't seem to be able to read and print the outcome. I am 100% sure that the actual command works, as I have tried to run the command in the terminal alone. I am not exactly sure why this problem is all of a sudden happening now.
The command is used to check whether a specific application is running and where it has been launched from.
The code I am using is the one below here.
try {
String procss;
Process pRun = Runtime.getRuntime().exec("ps -ef | grep google");
BufferedReader input = new BufferedReader(new InputStreamReader(pRun.getInputStream()));
while ((procss = input.readLine()) != null) {
if(!procss.contains("Contents"))
{
//Do something
}
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
To give an example of a command where it has worked without any problem, I have also just included a working code below. To show how I would actually like it to work, but just with the right command ps -ef | grep google instead.
try {
String procss;
Process pRun = Runtime.getRuntime().exec("top -F -R -o cpu");
BufferedReader input = new BufferedReader(new InputStreamReader(pRun.getInputStream()));
while ((procss = input.readLine()) != null) {
if(!procss.contains("testApplication"))
{
//Do something
}
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
I am not sure whether I need to use another method of reading the outcome or what I have to do for my code to actually work again.
I have a Hadoop YARN cluster set up on some machines at my university (all machines running Linux Fedora 25). When running a mapreduce job in YARN, I am unable to receive the output from a call I make to a separate program. Interestingly, if I run my job locally (configured in mapred-site.xml), my method for calling the program and receiving its output works just fine. Below is my executeShellCommand class, which is instantiated and used in my first map task.
public class ExecuteShellCommand {
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
String [] args = command.split(" ");
String cmd = args[0];
ProcessBuilder pb = new ProcessBuilder().command(cmd, args[1], args[2], args[3], args[4], args[5], args[6], args[7]).directory(new File("path to executable"));
p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
p.waitFor();
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
return output.toString();
}
}
Things I have made sure to check:
1) Permissions are appropriately set for all files/directories needed
2) Map tasks are run as current user (me), so no issues with illegal access
3) I am not receiving a file not found exception, so the path to the program I'm calling is correct
4) Checked the input/output stream for Process p (input stream set as java.lang.UNIXProcess$ProcessPipeInputStream#1000e80, output stream is null)
5) Instead of calling the program I need to use, I have tried a simple "echo" command, and could not receive that output either.
6) I have also tried using
p = Runtime.getRuntime().exec("myCommand")
but the results are the same (no output received)
As I already mentioned, when I run a job locally, my executeCommand method functions perfectly, and returns the output from the program I call. Only in YARN do the issues occur. I have a feeling that the problem caused by either not reading from the correct buffer, or the command issued to ProcessBuilder is never actually executed. I am quite stumped as to how to debug what is going on here, and any tips would be greatly appreciated!
After hours of trying all sorts of solutions, I figured out how to get the error stream from the process spawned with ProcessBuilder. Turns out when I set the working directory for the process, I forgot to update the path to one of the arguments I was passing it. D'oh!!!
Trying to build a basic launcher for a java game. I'm building the proper command to run the application. When the following command executes in the launcher, the launcher closes as expected, but the command doesn't appear to work - either it doesn't work or the game launches and immediately crashes.
When I print this same command to the console and copy/paste it into console and execute manually, it works perfectly.
/**
*
*/
protected void launch(){
currentStatusMsg = "Launching...";
String cmd = "java -jar";
cmd += " -Djava.library.path=\"" +nativesDirectory.getAbsolutePath() + "\"";
cmd += " \""+applicationJar.getAbsolutePath() + "\"";
System.out.println(cmd);
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);
//closeLauncher();
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
I tried adding something to read the output, but nothing is printed.
I was originally using the following format instead, but it has the same effect:
Process pr = Runtime.getRuntime().exec(new String[]{
"java",
"-Djava.library.path=\"" +nativesDirectory.getAbsolutePath() + "\"",
"-jar",
applicationJar.getAbsolutePath()});
Update I realized I was closing the launcher before allowing the debug code to run. The system only prints: "Exited with error code 1"
I finally was able to get the subprocess error to print. It states:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path
However, it should be available because the command I'm executing includes the library path, and when this exact command is run manually, it works fine.
the java command launcher is not a shell. don't use quoting and space separated commands because it won't end well. put each argument into a separate String without any extra quoting, and use the exec(String[]) method.
I am attempting to get output of a shell / bash script, that is run from a JAVA program, although I am not having much luck, the code is as follows:
GetStats(winhostname);
public static String winhostname "cmd /c hostname";
public static void GetStats(String operation)
{
try
{
Process p=Runtime.getRuntime().exec(operation);
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
if (operation.equals("winhostname"))
{
winhostnamevalue = line;
}
line=reader.readLine();
}
}
catch(IOException e1) {}
catch(InterruptedException e2) {}
}
This works on Windows fine, so I changed the value of winhostname to "sh namecheck.sh" (which simply echos the hostname) and the shell script is located in the same directory as the java / class file. Although when run I get a blank result, not null, just blank.
Try /bin/sh. I do not sure that when you are running program from java it has all environment that you have when you are working with shell.
If it does not work try to run some command (e.g. pwd). But provide full path. Then, when it works try your command again and be sure that it can find your script. For the beginning use absolute path. Then move to relative path.
Good luck.