Spawn a java process using runtime.exec() method
Hi,
This is my first post in this forum. I have a small problem. I am trying to spawn a java process using Runtime.getRuntime().exec() method in Solaris. However, there is no result in this check the follwoing program.
/* Program Starts here */
import java.io.*;
public class Test {
public static void main(String args[]) {
String cmd[] = {"java", "-version"};
Runtime runtime = Runtime.getRuntime();
try{
Process proc = runtime.exec(cmd);
}catch(Exception ioException){
ioException.printStackTrace();
/* Program ends here */
There is neither any exception nor any result.
The result I am expecting is it should print the following:
java version "1.4.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
Please help me out in this regard
Thanks in advance
Chotu.
Yes your right. It is proc.getInputStream() or proc.getErrorStream(). That is what I get for trying to use my memory instead of looking it up. Though hopefully the OP would have seen the return type of the other methods and figured it out.
Similar Messages
-
Start a new java process using Runtime.Exec() seems to ignore the -Xmx
I am working with a process that requires a minimum of 1.5 GB to run and works better if more is available.
So I am determining how much memory is available at startup and restarting the jre by calling
Runtime.exec("java -Dcom.sun.management.jmxremote=true -Xmx1500M -jar XXX.jar")
which reinvokes the same process with a new max memory size.
The initial call to the process is
java -Dcom.sun.management.jmxremote=true -Xmx3500M -jar XXX.jar
The initial call returns 3262251008 from Runtime.maxmemory()
When reinvoked through Runtime.exec() as above
Runtime.maxmemory() still returns 3262251008
Is there a way to separate the new process from the size specified by the parent process?That is strange. Here is a program I wrote which calls itself recursively.
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.ArrayList;
import static java.util.Arrays.asList;
public class MemorySize {
public static void main(String... args) throws IOException, InterruptedException {
System.out.println("Maximum memory size= "+Runtime.getRuntime().maxMemory());
if (args.length == 0) return;
List<String> cmd = new ArrayList<String>();
cmd.add("java");
cmd.add("-cp");
cmd.add(System.getProperty("java.class.path"));
cmd.add("-Xmx"+args[0]+'m');
cmd.add("MemorySize");
cmd.addAll(asList(args).subList(1,args.length));
Process p = new ProcessBuilder(cmd).start();
readin(p.getErrorStream());
readin(p.getInputStream());
private static void readin(final InputStream in) {
new Thread(new Runnable() {
public void run() {
try {
byte[] bytes = new byte[1024];
int len;
while((len = in.read(bytes))>0)
System.out.write(bytes, 0, len);
in.close();
} catch (IOException e) {
e.printStackTrace();
}).start();
}If you run this with the args 128 96 33 222 it prints out
Maximum memory size= 66650112
Maximum memory size= 133234688
Maximum memory size= 99942400
Maximum memory size= 35389440
Maximum memory size= 231014400 -
How to capture output of java files using Runtime.exec
Hi guys,
I'm trying to capture output of java files using Runtime.exec but I don't know how. I keep receiving error message "java.lang.NoClassDefFoundError:" but I don't know how to :(
import java.io.*;
public class CmdExec {
public CmdExec() {
public static void main(String argv[]){
try {
String line;
Runtime rt = Runtime.getRuntime();
String[] cmd = new String[2];
cmd[0] = "javac";
cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E.java";
Process proc = rt.exec(cmd);
cmd = new String[2];
cmd[0] = "javac";
cmd[1] = "I:\\My Documents\\My file\\CSM\\CSM00\\SmartQ\\src\\E";
proc = rt.exec(cmd);
//BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
input.close();
catch (Exception err) {
err.printStackTrace();
public class E {
public static void main(String[] args) {
System.out.println("hello world!!!!");
}Please help :)Javapedia: Classpath
How Classes are Found
Setting the class path (Windows)
Setting the class path (Solaris/Linux)
Understanding the Java ClassLoader
java -cp .;<any other directories or jars> YourClassNameYou get a NoClassDefFoundError message because the JVM (Java Virtual Machine) can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run.
javac -classpath .;<any additional jar files or directories> YourClassName.javaYou get a "cannot resolve symbol" message because the compiler can't find your class. The way to remedy this is to ensure that your class is included in the classpath. The example assumes that you are in the same directory as the class you're trying to run. -
Can we run a java application using Runtime.exec()?
Can we run a java application using Runtime.exec()?
If yes what should i use "java" or "javaw", and which way?
r.exec("java","xyz.class");The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
HIH
ClassLoader cl = null;
Class c = null;
Class cArr[] ;
Method md = null;
Object mArr[];
cl = ClassLoader.getSystemClassLoader();
try{
c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
} catch(ClassNotFoundException e) {
System.out.println(e);
cArr = new Class[1] ;
try{
cArr[0] = Class.forName("java.lang.Object");
} catch(ClassNotFoundException e) {
System.out.println(e);
mArr = new Object[1];
try{
md = c.getMethod("processPkt", cArr);
} catch(NoSuchMethodException e) {
System.out.println(e);
} catch(SecurityException e) {
System.out.println(e);
try {
processedPkt = md.invoke( null, mArr) ;
} catch(IllegalAccessException e) {
System.out.println(e);
} catch(IllegalArgumentException e) {
System.out.println(e);
}catch(InvocationTargetException e) {
System.out.println(e);
}catch(NullPointerException e) {
System.out.println(e);
}catch(ExceptionInInitializerError e) {
System.out.println(e);
} -
Using Runtime exec() method to run java files and return runtime errors
Hi
I'm writing a java editor and I use
Runtime.getRuntime().exec(command)
to compile the java files. That works fine and I deal with the returned errors using the getErrorStream().
My questions are:
1. Can I use the same technique for returning runtime errors. In any posts I've read the process runs from begining to end, returning the errors after completion. How do I return the errors of the app as they happen interactively?
2. If i cant use the exec and getErrorStream() methods then does anyone know how it is done?
Thanks in advance for any help!Read this:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
MOD -
Socket stays open after java process exits, Runtime.exec()
I have a program that does the following:
opens a socket
Does a runtime.exec() of another program
then the main program exits.
what i am seeing is, as long as the exec'd program is running, the socket remains open.
What can i do to get the socket to close?
I even tried to explicity call close() on it, and that didn't work. Any ideas would be great.
I am running this on WindowsXP using netstat to monitor the port utilization.
here is some sample code
import java.io.*;
import java.net.*;
public class ForkTest
public static void main(String[] args)
try
DatagramSocket s = new DatagramSocket(2006);
Process p = Runtime.getRuntime().exec("notepad.exe");
System.out.println("Press any key to exit");
System.in.read();
catch (IOException ex)
ex.printStackTrace();
}java.net.BindException: Address already in use: Cannot bind
at java.net.PlainDatagramSocketImpl.bind(Native Method)
at java.net.DatagramSocket.bind(DatagramSocket.java:368)
at java.net.DatagramSocket.<init>(DatagramSocket.java:210)
at java.net.DatagramSocket.<init>(DatagramSocket.java:261)
at java.net.DatagramSocket.<init>(DatagramSocket.java:234)
at ForkTest.main(ForkTest.java:11) -
Problem to execute cvs command using Runtime.exec method
Hello,
I want execute this cvs command, with this options:
cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d "2007/05/01<now" Project
I tried to execute with Runtime.exec() :
Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
But I have an error because the smaller character is interpretate as a redirection, no as a smaller symbol.
How I can do to use this command with Runtime.exec ?
Thanks.
Regards.Sorry,
I had a typing mistake.
I want say:
Runtime.exec("cvs -d :pserver:[email protected]:/home/cvs/cvsroot rlog -S -d \"2007/05/01<now\" Project");
Regards. -
Invoking "java myClass" using Runtime.Exec from a Java Stored Procedure
Hi All,
This is regarding the use of Runtime.getRunTime().exec, from a java programme (a Java Stored Procedure), to invoke another Java Class in command prompt.
I have read many threads here where people have been successuful in invoking OS calls, like any .exe file or batch file etc, from withing Java using the Runtime object.
Even i have tried a sample java programme from where i can invoke notepad.exe.
But i want to invoke another command prompt and run a java class, basically in this format:
{"cmd.exe","java myClass"}.
When i run my java programme (in command prompt), it doesnt invoke another command prompt...it just stays hanging.
When i run the java programme from my IDE, VisualCafe, it does open up a command prompt, but doesnt get the second command "java myCLass".
Infact on the title of the command prompt (the blue frame), shows the path of the java.exe of the Visual Cafe.
and anyway, it doesnt run my java class, that i have specified inside the programme.
Even if i try to run a JAR file, it still doesnt do anything.
(the JAR file other wise runs fine when i manually invoke it from the command prompt).
Well, my question is, actually i want to do this from a Java Stored Procedure inside oracle 8.1.7.
My feeling is, since the Java Stored Procedure wont be running from the command prompt (i will be actually invoking it through a Oracle trigger), it may be able to invoke the command prompt and run the java class i want. and that java class has to run with the SUn's Java, not Oracle JAva.
Does any one have any idea about it?
Has anyone ever invoked a java class or JAR file in command prompt from another Java Programme?
YOur help will be highly appreciated.
(P:S- Right now, my database is being upgraded, so i havent actually been able to create a Java Stored procedure and test it. But i have tested from a normal java programme running in command prompt and also from Visual Cafe).
Thanks in advance.
-- Subhasree.Hello Hari,
Thanks for your quick reply.
Can you please elaborate a little more on exactly how you did? may be just copy an dpaste taht part of teh code here?
Thanks a lot in advance.
--Subhasree -
Problem of executing a process under Linux using Runtime.exec
Hi, All
I am having a problem of executing a process under Linux and looking for help.
I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
1. I create a script to start this C program
2. I write a simple java application using Runtime.exec to execute this script
I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
I am using jre1.4.2_07 and running under Linux fedora 3.0.
Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?
-
Executing bat file without using Runtime.exec()??
Hi all
From my java App ,I am running a bat file. This is what I did:
When I press 'execute' button inside my App, it runs a bat file through Runtime.exec() method. Since exec() runs it through cmd.exe, get a DOS window when I press Execute button. If I manually runs my app from command promt , I dont get it. But I have to create a short cut of my main class in the desktop. This is happening when I run my app from desktop icon.
Now I want to eleminate DOS popup everytime I press execute button. Would anyone pls give an idea how to run bat file without using Runtime.exec()? Any suggestion will be helpful.
Thanksjscell
Thanks for taking time to answer to my problem .
Here is what my problem: I create a shortcut of my main class in the desktop. Through this shortcut ,I run my java App. My App has a execute button, When I press this button , It run another bat file through Runtime.exec() method, and show some result in the result PAnel. NOw what happen , I get a DOS command window , everytime I press execute button. , Which is very annoying . But If I run my App thorugh command promt by executing: "java myApp", then I dont get this DOS popup. But I have to create a shortcut in the desktop, so other can use it conveniently.
NOw I am not sure why I am getting this DOS window in the middle of my Application. IS it for using Runtime.exec() method? or for running bat file through my application? Can anyone pls tell me? I am kind of new to java, and I am learning lot of stuff from this forum .
Would u pls suggest me about how to eleminate this DOS popup when I press execute button.
Regrds -
Java's Runtime.exec() method
When you shell out to java's Runtime.exec() method, are the process name and arguments the same for the child process that is spawned.
We see duplicated processes about the time when our logs tell us this command was run. However, we cannot seem to reproduce this. Has anyone else seen anyone this before?That's what I though too. But check this out . . .
Our code looks as follows:
private Runtime rt;
private Process p;
rt = Rutime.getRuntime();
p = rt.exec(command);
This exec() call creates a new process, which is a child of the java process that runs this command. The final process looks like the "command" string that is passed to the exec() method call. In our case, the command is a call to the /usr/bin/mail utility to send out faxes and emails.
We ran a very tight loop executing the rt.exec() call over and over. What we found was that for a minor fraction of a second, the newly created process looks just like the original process including the same arguments. However, the PID's indicated that one process was the child of the other. This is why it looked like we had 2 of the same processes. WILD!
Thanks guys! -
Using Runtime.exec to execute Java.exe
I am trying to use Runtime.exec to spawn a thread that runs java.exe, but havn't had any luck. I have two versions of code, the first one works (example 1), but I want to eliminate the use of "cmd /c" to keep system independance. The second example (example 2) does not work. Both versions work if invoked from the command line. I'm running Win2000. Any Ideas?
Example 1:
aProcess = aRuntime.exec("cmd /c java.exe
-cp "<MyClassPathHere>" <arg1> <arg2> <arg3> <arg4> <arg5>");
Example 2:
aProcess = aRuntime.exec("java.exe
-cp "MyClassPathHere" <arg1> <arg2> <arg3> <arg4> <arg5>");I think you mix two concepts: "threads" and "processes". A "thread" is a thread of execution inside the VM, but you want to actually start a new VM in a new process, which is an OS level thing, right?
I've tried Idea 2 also, same result: works if
i specify cmd c/, doesn't if I don't.It should work if java.exe is in your path... are you taking care of the standard streams of your process? -
Using runtime.exec,process streams
Hi all,
I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
So I have 2 questions.
1. Can I forcibly delete these files some other way.
2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
Thanks for your help.
VinnyI tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
try{
Process p = rt.exec("cmd.exe /c start deletefiles.bat");
InputStream ins = p.getInputStream();
byte[] bytearray = new byte[1024];
int bytecount;
String dos_string="";
BufferedInputStream bis = new BufferedInputStream(ins);
while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
String str = new String(bytearray,0,bytecount);
dos_string += str;
System.out.println("dos string is" +dos_string);
catch (Exception e) {
System.out.println("Error: " + e); -
Using Runtime exec() to open java on other directory
HI, I have a little problem and i hope everyone can help me out abit. You see when u use Runtime.exec(), how to you use it so that when the file you want to open is different from your program directory.
For example,
my program is in c:\windows\desktop
but the file i want to open eg. Somthing.class is in c:\my documents\
How do I open it using java and i wish to open the file using the java command. Thank a millionRuntime.getRuntime().exec("cmd /c start /d\"C:\\my documents\" java.exe Somthing");
Can someone explain the /c start /d\"C:\Mydocuments\" java.exe Somthing.
And I try to use ping in RunTime.exec,how do I construct the string?And how do i get the result of the ping?
Thanks -
The Runtime.exec methods doesn't work well on Solaris ???
I have two threads and I set the different running time.
I use Runtime.exec to a run the command and use Process to get the process.
It works properly in the windows2000 platform.
However, when I transfer the platform to Solaris...and run the program...
Two threads always at the same time....It is very wired....I always debug
for 2 days....
(at first I run "vmstat 1 2" command, later I change to "ls","rmdir"....etc,
all of them don't work.....
If I close the Runtime.exec..........Everything works well......)
And I study the API. I found this message...
The Runtime.exec methods may not work well for special processes on certain
native platforms, such as native windowing processes, daemon processes,
Win16/DOS processes on Win32, or shell scripts. The created subprocess does
not have its own terminal or console.
Could someone share her/his experience.....:(
And if any other way I can run command inside java code instead of
Runtime.exec.....???
Please reply my mail to [email protected] I do appreciate your kindly &
great help!!!!!!!!
This is my code.......
import java.io.*;
import java.lang.*;
import java.util.*;
* <p>ServerThread1</p>
* <p>??�X???��?�D???�X???, "Vmstat 1 2".</p>
class ServerThread1 extends Thread{
private ServerAgent Sa;
public ServerThread1 (String Name, ServerAgent Sa){
super(Name);
this.Sa = Sa; file://Assign ServerAgent reference Sa
public void run(){
while(true){
try{
Thread.sleep(5000);
catch (Exception e){
System.out.println("ServerThread1 fails");
System.out.println("Thread1 is running.");
try {
Runtime rt1 = Runtime.getRuntime();
Process proc1 = rt1.exec("mkdir"); ------>If I close
rt1.exec , two threads works seperately...........:(
catch (Exception e) {
System.out.println("Thread1 Error");
class ServerThread2 extends Thread{
private ServerAgent Sa;
public ServerThread2 (String Name, ServerAgent Sa){
super(Name);
this.Sa = Sa;
public void run(){
while(true){
try{
Thread.sleep(15000);
catch (Exception e){
System.out.println("ServerThread2 fails");
System.out.println("Thread2 is running.");
try {
Runtime rt2 = Runtime.getRuntime();
Process proc2 = rt2.exec("vmstat 1 2"); ----->If I don't run
the rt2.exe, two threads work seperately....
catch (Exception e) {
System.out.println("Thread2 Error");
public class ServerAgent{
private Vector v1 = new Vector();
private Vector v2 = new Vector();
private Hashtable currentData = new Hashtable();
private static String startUpSwap = null;
private static String startUpMem = null;
public static void main(String[] arg) {
ServerAgent s = new ServerAgent();
ServerThread1 st1 = new ServerThread1("Thread1",s);
ServerThread2 st2 = new ServerThread2("Thread2",s);
st1.start();
st2.start();If I close the Runtime.exec..........Everything works
well......)You don't empty the output of the command, that blocks the process.
A citation from
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Why Runtime.exec() hangs
The JDK's Javadoc documentation provides the answer to this question:
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.
Try out something like this:
String s;
try {
Process myProcess =
Runtime.getRuntime().exec("ls -l"));
DataInputStream in = new DataInputStream(
new BufferedInputStream(myProcess.getInputStream()));
while ((s = in.readLine()) != null) {
out.println(s);
catch (IOException e) {
out.println("Error: " + e);
}Another source of trouble under Unix is not having the correct permission for that user that executes the Java VM, which will be the permissions for the spawned subprocess. But this probably not the case, as you see something after exit.
Regards,
Marc
Maybe you are looking for
-
I need to know how to get back into my laptop!!! Please help.
-
Hello, I want to run TS sequences programatically, like a customized OI. I don't need any buttons, I plan to run everything programatically. For that I have created a VI, where I connect a SequenceView ActiveX object to the ExecutionViewMgr. The sequ
-
Using Time Capsule as External HD
How can I use my time capsule as an external HD? It works with time machine for backup but I can't drag and drop files onto it or make new folders...
-
My company has 2 development clients. One client for configuration. One client for unit testing. All configuration and developments should be made in the configuration client, then copy to the unit testing client. Then transport to test and productio
-
Transferting file without WiFi
Is here a file management utility availabe for transferring the files from PC to Iphone by using USB connection? thanks