How to read lines from a C script from Java's BufferedReader? - java

I'm running this java program on a raspberry pi. The program is supposed to run the script "hello_pixy" and scan what it prints out. When I run hello_pixy manually, it prints out lines normally (Via C's printf line). But when I run the program, nothing is printed out and the BufferedReader didn't read any lines.
If I substitute the script for something like "ls", then the BufferedReader reads it and prints it out. Is there a way I can change the "printf"s in C to send to the InputStream (I don't really know C, just enough from Java experience)?
Process process = null;
try {
process = Runtime.getRuntime().exec("sudo .ss/pixy/build/hello_pixy/hello_pixy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //for Windows
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String print = "";
try {
while ((line = reader.readLine()) != null) {
print += line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nCodescan:\n\n" + print);
The code I'm executing is here: https://github.com/De-etz/pixy/blob/master/src/host/hello_pixy/hello_pixy.cpp

You're doing this back to front. You must read all the process's output first, and then call waitFor(). Your way you will probably just deadlock, as the process can't exit until it has produced all its output, and if you're not reading it, it will eventually block.
Notes:
C is not a scripting language, and a compiled program is not a script by definition.
Code that depends on the success of code in a prior try block must be inside that try block. At present you are continuing after exceptions as though they didn't happen. Don't write code like this.

Related

How could I pass in commands into a terminal that is already running in java (linux)

I have been researching how to run a terminal command in java. I am doing this to make a program I can use to ssh into another pc (just as a project). How could I keep continuing putting commands in this terminal? If I run this I get a message to put in my password and if I do so it will print out what the messages the terminal spits out at the :
while((line = in.readLine()) != null){
System.out.println(line + "\n");
}
line, but a few seconds after that my program will stop working.
I currently have a GUI that is just a button and if I press the button it will run this code. Could someone help me to fix the issue of it stopping and give me information on how I could continue to put commands into the terminal? Thanks.
Process p = null;
String[] command = {"/bin/sh", "-c", "ssh 192.168.2.100"};
ProcessBuilder pb = new ProcessBuilder(command);
String line = null;
try {
term = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
try {
while((line = in.readLine()) != null){
System.out.println(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can not pass the argument to live JVM, But there is way in which you can modify the some of the parameters which done using JMX, with this you can connect to live JVM and send the parameters. which will be taken the effect immediately.
Hope that helps

Using Runtime.getRuntime().exec() to run perl code in java

I have a perl script called pbp that takes an html file as an argument and then creates an output file. Here is my current code. Infile is obtained earlier from a JFile Chooser. I don't get any errors but there is no ouput from the perl script.
try {
Process p = Runtime.getRuntime().exec(new String[] {"perl", "C:\\Users\\Roger\\Downloads\\The_Long-Awaited_Product_Specification_and_Sample_Files\\casey\\pbp", inFile.getAbsolutePath()});
p.getInputStream().close();
p.getOutputStream().close();
p.getErrorStream().close();
System.out.println(p.waitFor());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
You will not get the output of per script directly. You need to capture it using the below code:
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
// read the output from the command
System.out.println("EXE OUTPUT");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}

Running a Perl script in Java using ProcessBuilder

I am using ProcessBuilder in Java to run a Perl script. When I run the Perl script while printing the InputStream of the process, the Java program seems to run for the duration of the Perl script. However if I comment out the getOutPut method in main the Java program terminates very fast and the Perl script does not run at all. Why does this occur?
private final static String SCENARIO = "scen";
/**
* #param args
*/
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("perl", SCENARIO+".pl");
pb.directory(new File("t:/usr/aman/"+SCENARIO));
try {
Process p = pb.start();
getOutput(p.getInputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List getOutput(InputStream is, boolean print) {
List output = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = null;
try {
while ((s = reader.readLine()) != null) {
output.add(s);
if(print){
System.out.println(s);
}
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
return null;
}
return output;
}
Likely the OS's output stream buffer for your PERL script process gets filled because nothing is emptying this buffer, and this will kill the process. You need to gobble the output stream for this reason which is what your getOutput method does for you.
Please read the classic reference on this problem: When Runtime.exec() won't. Per this article:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

how to pass the arguments to the shell command through java?

I am new to this kind of integration of java with Unix.
what i am trying to do is
String command="passwd";
Runtime rt=Runtime.getRuntime();
try {
Process pc=rt.exec(command);
try {
pc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader buf = new BufferedReader(new InputStreamReader(pc.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
BufferedReader buf1 = new BufferedReader(new InputStreamReader(pc.getErrorStream()));
String line1 = "";
while ((line1=buf1.readLine())!=null) {
System.out.println("Error--"+line1);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("IOException---"+e1.getMessage());
}
now when i am trying to pass the "passwd" command the Unix environment goes to suspended mode.
I want to know how can i pass the old password ,new password and confirm new password to the shell using the java code.
You need to pass it in using the confusing named Process.getOutputStream(). From the doc:
Gets the output stream of the subprocess. Output to the stream is
piped into the standard input stream of the process represented by
this Process object
Note that you need to capture the processes stdout/err simultaneously to avoid blocking. See this answer for more details.
There is a utility called expect. If u installed u can pass argument for any thing. So construct as string execute by
String ConstructedCommand;
Process p=Runtime.getRuntime().exec(ConstructedCommand);
This link will be deserve your need. http://linux.die.net/man/1/expect

Read from another process' output stream

i wanted to read the output-stream of a c-Application in my Java program. iremoted (available here: Link) is a C-Application that puts out seperate lines like "0x19 pressed" if a button on my Apple Remote is pressed. If i start the iremoted program everything is doing well and these separate lines are shown on my screen everytime I pressed a button.
Now I wanted to read the output-stream of the c-application in my Java application to process inputs of the Apple Remote in Java projects.
Unfortunately i don't know why no input is regocnized?
I tried it with a simple HelloWorld.c program and my program responded as intended in this case (prints out HelloWorld).
Why doensn't it work with the iremoted program?
public class RemoteListener {
public void listen(String command) throws IOException {
String line;
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
} catch (Exception e) {
System.err.println("Could not execute program. Shut down now.");
System.exit(-1);
}
Reader inStreamReader = new InputStreamReader(process.getInputStream());
BufferedReader in = new BufferedReader(inStreamReader);
System.out.println("Stream started");
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
System.out.println("Stream Closed");
}
public static void main(String args[]) {
RemoteListener r = new RemoteListener();
try {
r.listen("./iremoted"); /* not working... why?*/
// r.listen("./HelloWorld"); /* working fine */
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
stdout is buffered and it's not automatically flushed if you are not writing to screen. Add:
fflush(stdout);
after:
printf("%#lx %s\n", (UInt32)event.elementCookie,
(event.value == 0) ? "depressed" : "pressed");
iremoted is likely writing to stderr if a hello world program works. You would want the error stream in that case. I'm not sure how this works for your hello world case - I think you're doing the wrong thing here:
new InputStreamReader(process.getInputStream());
should be
new InputStreamReader(process.getOutputStream());
or
new InputStreamReader(process.getErrorStream());

Categories

Resources