Not getting any output after calling C executable file from Java code - java

I am trying to execute the C code from Java code which is already compiled and executed, but, I am not getting any output from the executable file. Can anyone help me to complete this task?
Code is as follows.
public class Test {
public static void main(String args[]) {
try {
Process processCompile = Runtime.getRuntime().exec("e:/Sample.exe");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}

Try this:
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(processCompile .getInputStream()));
// read the output from the command
System.out.println("EXE OUTPUT");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}

This method would work only if you run the java program with admin privileges.
If you have privileges, then can you try running your process under "cmd" shell (Which is forked by your java process). An implementation do so this is done here "LinuxInteractor" ( But is in linux). Just minor change needed to port to Windows version.
Finding hard and soft open file limits from within jvm in linux (ulimit -n and ulimit -Hn)

Related

how can I execute "java" command by java code?

I'm trying to run a multi-agent system using JADE by code.
Usually, I can run the jade system by command line using the following command:
java jade.Boot -gui
It also works well using Netbeans IDE by changing the project properties and pointing the run configuration to the jade.Boot class.
My problem is: I want to run this system by java code... let's say, when a user clicks a button, and as far as I know, this command specified above should work using the following code:
Process p=null;
try {
p = Runtime.getRuntime().exec("java jade.Boot -gui;");
}
catch (IOException ex) {
Logger.getLogger(SimulationCreator.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
try {
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} catch (IOException ex) {
Logger.getLogger(SimulationCreator.class.getName()).log(Level.SEVERE, null, ex);
}
But I'm getting nothing, neither the JADE system is running nor I'm getting any error.
What am I missing ?
P.S.: I'm working on ubuntu 20.0.
P.S.: running other commands by code like "ps -aux" works very well!
Your problem may be a difference between PATH of the current running VM, compared the shell (bash etc) you use and implicit passing of CLASSPATH. Check the location of java which which java in the shell that works and try using in your exec.
Also you won't see all issues when running as you don't access the error stream at same time as the output stream, changing to ProcessBuilder allows easier debugging as you can redirect the out/err streams to a file. But if JADE runs for a long time or produces a lot of output you should consumer STDOUT+ERR in background threads.
Try this in jshell:
String[] cmd = new String[]{"java", "jade.Boot", "-gui"};
ProcessBuilder pb = new ProcessBuilder(cmd);
File fileOut = new File("stdout.log");
File fileErr = new File("stderr.log");
pb.redirectError(fileErr);
pb.redirectOutput(fileOut);
Process p = pb.start();
int rc = p.waitFor();
String stdout = Files.readString(fileOut.toPath());
String stderr = Files.readString(fileErr.toPath());
System.out.println("Exit : "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****"));
System.out.println("STDOUT : "+stdout);
System.out.println("STDERR : "+stderr);

Java program to run shell commands from a windows machine

I am trying to run a Java program to shell out commands on a remote (Linux) machine. I can get the putty.exe to run and then connect to the machine using SSH keys. But am not able to run the actual commands such as "bash" "ps-ef" or "ls -la". Currently using the Java runtime.exec, not sure if using the java.lang.ProcessBuilder would help? What am I doing wrong ? Any help/guidance would be greatly appreciated.. Thanks in advance
package hello;
import java.io.*;
public class RuntimeExample {
public static void main(String args[]) throws IOException {
try{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[]{"C:\\Users\\yky90455\\Desktop\\putty.exe","abc#login.testserver.helloworld.co.uk","bash", "ps -ef"});
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running the command is:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try Jsch From here to get the shell scrips executed from Java to some remote Linux machine. I have worked on this and it was really fun.although you may find little shortage of docs for understanding this but you can overcome that easily.
Also consider ExpectJ which is a wrapper around TCL Expect. The project does not appear to have any active development since mid 2010, but I have used it for SSH in the past.
http://expectj.sourceforge.net/apidocs/expectj/SshSpawn.html
Thanks for all your answers. I tried Ganymed SSH-2 library. It works well for the basic commands on the remote machine. I will have to explore other APIs in case I run into any limitation with SSH-2.
public class triggerPutty {
public static void main(String[] a) {
try {
String command = "putty.exe user#abc.text.com -pw password -m C:\\containing_comman.txt";
Runtime r = Runtime.getRuntime();
Process p = null;
p = r.exec(command);
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
-m helps to run your command from that file.
You can keep N number of commands in that file.. ## Heading ##

how to launch a shell script in a new gnome terminal, from a java program

I'm trying to run a shell script (say myscript.sh) from a java program.
when i run the script from terminal, like this :
./myscript.sh
it works fine.
But when i call it from the java program, with the following code :
try
{
ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);
pb.environment().put("PATH", "OtherPath");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line ;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
}catch(Exception e)
{ e.printStackTrace(); }
}
It doesnt goes the same way.
Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.
Question : Is there some way to launch this script in a new terminal using java.
PS : i've found that "gnome-terminal" command launches a new terminal in shell,
But, i'm unable to figure out, how to use the same in a java code.
i'm quite new to using shell scripting. Please help
Thanks in advance
In java:
import java.lang.Runtime;
class CLI {
public static void main(String args[]) {
String command[] = {"/bin/sh", "-c",
"gnome-terminal --execute ./myscript.sh"};
Runtime rt = Runtime.getRuntime();
try {
rt.exec(command);
} catch(Exception ex) {
// handle ex
}
}
}
And the contents of the script are:
#!/bin/bash
echo 'hello!'
bash
Notes:
You'll do this in a background thread or a worker
The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
The shell script is located in the same path as the calling Java class.
Don't overrwrite your entire PATH...
pb.environment().put("PATH", "OtherPath"); // This drops the existing PATH... ouch.
Try this instead
pb.environment().put("PATH", "OtherPath:" + pb.environment().get("PATH"));
Or, use the full directories to your commands in your script file.
You must set your shell script file as executable first and then add the below code,
shellScriptFile.setExecutable(true);
//Running sh file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_SHELL_SCRIPT_FILE+File.separator+shellScriptFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("Shell script executed properly");
}
This worked for me on Ubuntu and Java 8
Process pr =new ProcessBuilder("gnome-terminal", "-e",
"./progrm").directory(new File("/directory/for/the/program/to/be/executed/from")).start();
The previous code creates a new terminal in a specificied directory and executes a command
script.sh Must have executable permissions
public class ShellFileInNewTerminalFromJava {
public static void main(String[] arg) {
try{
Process pr =new ProcessBuilder("gnome-terminal", "-e", "pathToScript/script.sh").start();
}catch(Exception e){
e.printStackTrace();
}
}
}

Run monkey from java

I have this script in file script.txt
And I run this like this
monkeyrunner /home/user/script.txt
this is my script.txt
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import time
device = MonkeyRunner.waitForConnection("wait forever","emulator-5554")
package = 'com.pak.pak1'
activity = 'com.pak.pak1.MyActivity'
runComponent = package + '/' + activity
# Runs the component
device.startActivity(component=runComponent)
time.sleep(1)
The thing I want to do is to run the script from java
This code runs a shell command for example to srart the script
try {
new Thread() {
public void run() {
Process p;
try {
p = Runtime.getRuntime().exec("monkeyrunner /home/user/script.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
p.waitFor();
} catch (Exception e) {
//e.printStackTrace();
}
}
}.start();
} catch (Exception ie) {
}
And finally mu question is how can I directly from java run the monkey runner commands, I do not want to have the script.txt file. Is this possible ? My goal is to run the monkey runner but I do not want to have the script.txt file
Apparently, if you include the MonkeyRunner chimpchat.jar (and it's jar depedencies) on your classpath, then you can call the monkey runner Java classes directly inside your Java application. Check out this class and this class that make up an example:
Another thread on this subject
This looks awfully complicated, but still..
monkeyrunner can run interactively, so write directly to stdin (get it from p.getOutputStream()) all strings you want it to run.
you might need to exhaust the stdout before issuing any command, but I don't think that will be the case.

using Runtime.exec() in Java

What do you have to do in Java to get the Runtime.exec() to run a program that is on the path? I'm trying to run gpsbabel which I have put into the path (/usr/local/bin).
public class GpxLib {
public static void main(String[] args) {
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("gpsbabel -i garmin -f usb: -o gpx -F -");
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true)
{
String s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.readLine();
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
I added a call to System.out.println(System.getenv("PATH")); which only prints out
/usr/bin:/bin:/usr/sbin:/sbin
so for some reason /usr/local/bin doesn't show up. Looks like this is a MacOSX question or an Eclipse question, not a Java question. edit: asked this question on superuser instead.
It will inherit the path from the Java process. So whatever environment the Java process has, the spawned process will have as well. Here's how to check the environment:
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
Have you set the PATH and exported it ? If you don't export it, then it's not available to subprocesses.
Additionally, you must consume stdout and stderr concurrently, to prevent blocking. Otherwise stuff will work in some circumstances, then your spawned process will output a different quantity of data and everything will grind to a halt.
See this answer for more details.
Here is the solution:
ProcessBuilder proc = new ProcessBuilder("<Directory PAth>" + "Executable.exe");
proc.redirectOutput(ProcessBuilder.Redirect.INHERIT);
proc.directory(fi); //fi = the output directory path
proc.start();
is the path where program\application's excutable is located e.g "C:\MyProg\"

Categories