Runtime.getRuntime().exec hangs and doesn't print the output
Hi,
I have written the following code to execute the command "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt" and print the output in 25_showoutpout.txt file.
import java.io.*;
public class ExecTest{
public static void main(String args[]) throws IOException{
String args1 = "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt";
try{
Process p=Runtime.getRuntime().exec(args1);
int i = p.waitFor();
System.out.println("Done.with time "+i);
}catch(Exception e){
System.out.println("The error is "+e);
But this program hangs and creates a blank 25_showoutpout.txt file.In the process list I can see the process running, but it doesn't redirect the output in the txt file.When i run the command from the command line it runs fine.Please help me.
Thanks in advance
Hi,
I have written the following program to get the output.But still the required output is not coming in the console file.Only the messages that gets printed in the parent console that is coming in the file.But the expected output is to get the messages from the child window which gets executed while the .exe runs.
import java.io.*;
public class RuntimeExecTest{
public static void main(String args[]){
String s = null;
String result= null;
int count =0;
try{
// read the output from the command
String cmd = "cmd.exe /c D:/installer/PsTools.zip/PsTools/psexec.exe ipaddress -u userid -p password -l -c excute.exe >> C:/RuntimeExec_25.txt";
Process p = Runtime.getRuntime().exec(cmd);
InputStream is = p.getInputStream();
// Get the std in to the process.
OutputStream os = p.getOutputStream();
// Get the std err from the process.
InputStream es = p.getErrorStream();
// Create readers for those streams.
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
String line;
// Read STDOUT into a buffer.
// If no STDOUT check STDERR.
while((line = errReader.readLine()) != null){
// Do something with data here if you wish.
System.out.println( line );
while((line = reader.readLine()) != null){
// Do something with data here if you wish.
System.out.println( line );
System.exit(0);
catch( Exception ex )
ex.printStackTrace();
}
Similar Messages
-
When I print a Word for Mac document to a shared printer (that is connected to my iMac) from my Macbook Pro, print preview looks fine but the printed page has too much blank space at the top and doesn't print the bottom few lines. I have tried to adjust the margins and the page setup settings but to no avail. It used to print fine until recently. Is there a way to fix it so that the printer prints what print preview shows?
I should add that when I e-mail this document to myself and print it directky from the iMac, it prints fine.
-
How would you capture the stdout of Runtime.getRuntime().exec())?
Say you wanted to execute PKZIP25.exe from java using Runtime.getRuntime().exec(). How would you capture the output of PKZIP25 (the console IO) in a file so you could check the results?
Thanks
Bill BlalockThanks.
Could you explain a little more?
The program I am calling seems to be executing, as far as Java is concerned, but nothing happens. I imagine I have made mistakes in calling it but can't see the output to the console.
Should I use Runtime.getRuntime().exec() or Runtime.exec() for something like this?
I appreciate the help!
Bill B. -
Runtime.getRuntime().exec() and Garbage Collection
I am programming a piece of software in both Java and C that has some strict real time requirements. Garbage collection, which pauses all threads in Java, sometimes causes loss of incoming data. In order to get around this, I am thinking to start another process using Runtime.getRuntime().exec("c_program") and using interprocess controls (in a UNIX environment) to retrieve data from the new process.
My only worry is that the Process created by the above call would be a child process of whatever JVM thread created it, (as far as I understand, the JVM implementation in Unix uses multiple processes) and would also be paused when garbage collection occurs. Does anyone know the implementation of the exec functionality and the JVM well enough to say that this will or will not happen?
Thanks in advance,
BenjaminYou're going to create a whole new process? I don't
know what a "child process" means, but Runtime.exec()
gets the operating system to produce an entirely new
process, outside the JVM. However if it produces
output on stdout or stderr, you're going to have
threads in your JVM that read that output, otherwise
that process will hang.
Why is your idea better than just calling the C
program via JNI?Thank you both for your replies. My plan was to create a whole new process, yes. In UNIX, a process C is created by another process P using fork() or the exec() family. Process P is then the parent of process C, and process C is the child of Process P. P has an amount of control over C since it can send various signals to pause, kill, etc to C.
My concern was that the JVM implementation would use these signals to implement the pause of all threads before garbage collecting. If it did, it may also pause the Process that it spawned from the Runtime.exec() call. Pausing my C program in this manner would cause the loss of data I was trying to avoid in the first place.
My plan for the new process was not to produce anything on stdout or stderr, but to pass data back to the JVM using ipc (interprocess communication) resources of UNIX. I would have to use the JNI to access these resources.
The whole reason for wanting to do this is to avoid the pause during garbage collection that all Java Threads experience. If I were just to call the C program through the JNI with a normal Java Thread as I think you were suggesting, this Java Thread would still be paused during garbage collection.
To the second reply about RTSJ, I had heard about this but couldn't find info about it! Thanks for the link. I'm checking it out at the moment. The java runtime must be considerably different for the specifications I see that they guarantee.
Again, thanks for the replies,
Benjamin -
Running curl command from a java program using Runtime.getRuntime.exec
for some reason my curl command does not run when I run it from within my java program and errors out with "https protocol not supported". This same curl command however runs fine from any directory on my red hat linux system.
To debug the problem, I printed my curl command from the java program before calling Runtime.getRuntime.exec command and then used this o/p to run from the command line and it runs fine.
I am not using libcurl or anything else, I am running a simple curl command as a command line utility from inside a Java program.
Any ideas on why this might be happening?thanks a lot for your response. The reason why I am using curl is because I need to use certificates and keys to gain access to the internal server. So I use curl "<url> --cert <path to the certificate>" --key "<path to the key>". If you don't mid could you please tell me which version of curl you are using.
I am using 7.15 in my system.
Below is the code which errors out.
public int execCurlCmd(String command)
String s = null;
try {
// run the Unix "ps -ef" command
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
return(0);
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
return(-1);
} -
Runtime.getRuntime().exec() does not return
Hello,
I am running into a case where the call to Runtime.getRuntime.exec(command) does not return. The scenario is that the main thread spawns another thread which calls the Runtime.exec(). Since the call does not return, both threads seems to be hung. The jstack output from the main thread shows
----------------- t@2 -----------------
0xfeedab45 ___lwp_cond_wait + 0x15
0xfeb4030d void os::PlatformEvent::park() + 0xa9
0xfebadd48 void ObjectMonitor::wait(long long,bool,Thread*) + 0x26c
0xfe770287 void ObjectSynchronizer::wait(Handle,long long,Thread*) + 0xef
0xfe76ffbb JVM_MonitorWait + 0x20f
0xfb20a032 * java.lang.Object.wait(long) bci:0 (Interpreted frame)
0xfb20308d * java.lang.Thread.join(long) bci:38 line:1143 (Interpreted frame)
0xfb20308d * java.lang.Thread.join() bci:2 line:1196 (Interpreted frame)
0xfb20308d * DataLoader.checkThreadGroup() bci:92 line:316 (Interpreted frame)
0xfb202f27 * DataLoader.checkTables(int) bci:1 line:336 (Interpreted frame)
0xfb202f69 * DataLoader.runLoad(int, java.lang.String, java.lang.String, java.lang.String, com.sabre.fltsked.apm.util.FSIOHelper)
... more below ....
So it is waiting for the spawned thread on a join()
And the jstack dump for the thread that called exec() is
----------------- t@70 -----------------
0xfeed7409 __lwp_park + 0x19
0xfeed1be7 cond_wait_queue + 0x5e
0xfeed1f64 cond_wait_common + 0x1db
0xfeed20d2 condwait + 0x7b
0xfeed20fd cond_wait + 0x21
0xfeed2136 pthread_cond_wait + 0x1b
0x9741082a soft_delete_object_cleanup + 0x57
0x97410906 soft_delete_object + 0x5b
0x97410953 soft_delete_all_objects_in_session + 0x2e
0x97407b7a soft_delete_session + 0xec
0x97407860 soft_delete_all_sessions + 0x3c
0x97402525 finalize_common + 0x66
0x974026ae softtoken_fini + 0x34
0x974355f9 _fini + 0x21
0xfefdd49a remove_hdl + 0x766
0xfefd8be9 dlclose_core + 0xb1
0xfefd8c1d dlclose_intn + 0x21
0xfefd8c96 dlclose_check + 0x2a
0xfefd8d00 dlclose + 0x38
0x97480aeb pkcs11_slottable_delete + 0xb1
0x9747c691 finalize_common + 0xe2
0x9747c6e0 pkcs11_fini + 0x3e
0x9747c3bf pkcs11_fork_child + 0x73
0xfee628b8 postforkchild_handler + 0x2f
0xfeeca9ec fork + 0x12e
0xfe338029 Java_java_lang_UNIXProcess_forkAndExec + 0x395
0xfb20a032 * java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) bci
:0 (Interpreted frame)
0xfb202f69 * java.lang.UNIXProcess.<init>(byte[], byte[], int, byte[], int, byte[], boolean) bci:62 line:53 (Interpreted frame)
0xfb20308d * java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) bci:182 line:65 (Interpreted frame)
0xfb202f27 * java.lang.ProcessBuilder.start() bci:112 line:452 (Interpreted frame)
0xfb202f27 * java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) bci:16 line:593 (Interpreted frame)
0xfb202f27 * java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File) bci:69 line:431 (Interpreted frame)
0xfb202f27 * java.lang.Runtime.exec(java.lang.String) bci:4 line:328 (Interpreted frame)
0xfb202f27 *SQLLoad(java.lang.StringBuffer) bci:181 line:51 (Interpreted frame)
0xfb202e61 *FSLoadThread.run() bci:84 line:54 (Interpreted frame)
The command I am trying to exec is "sqlldr" and I do have it in my PATH variable. Why is that the call to exec does not return? Any ideas?
This is on jdk1.6.0_17
Thanks,
Bijoy.It has definitely forked, and this is the child process. It says so. If it was the parent process it would just show Java code related to launching processes. That does not involve PKCS11. After the fork there are two identical processes with the same stack: the child process of the fork goes on to replace itself with the target command via Unix exec(), which it doesn't look like it is succeeding at. The parent process doesn't do much at all, probably just housekeeping and then a Unix wait() for Process.waitFor() to hook into.
-
Runtime.getRuntime().exec - relies on the J2RE?
Well here is a problem...
My program works fine using the Runtime.getRuntime().exec command, and the program works as-intended on my computer. But that's because I have the latest and greatest Java apparel (especially the J2RE).
Now, a friend of mine who does not program, took my program and tried it on his computer. It worked (the GUI loaded and buttons functioned) but it didn't actually do anything other than serve as a nice-looking GUI lol.
The problem was, it was creating the file I had it create (using FileWriter) but it wasn't EXECUTING that file like I designed the program to.
I used the Runtime.getRuntime().exec to execute the file - my question is, if the person doesn't have the Java Runtime Environment, will that command work? He clearly has Java on his computer (the GUI loaded) but he might not have the J2RE...
Any thoughts? Any suggestions for an alternative way to execute a file?
Thanks!
-JoshI don't understand why this wont work on other
people's computers...
I create the file "commands.bat" in their C:\
directory. I then have the following command to
execute it:
Runtime.getRuntime().exec("cmd.exe /c
\"C:\\crasher.bat\"");It works perfect for me... But it doesn't work for
other people. For other people, it creates the batch
file in the right place, it just wont execute it and
I am not sure why...
-JoshYou said "commands.bat" but your code is executing "crasher.bat". I have the feeling you're trying to crash their computers or something?
cmd.exe is an executable on certain flavors of Windows. Other flavors of Windows have command.exe, not cmd.exe. So you have to pick the same platform, or make the actual command that you execute be dynamic (read it from a property file to determine what to execute).
Go to those other machines and see if you can execute that same command from the command line. Do some debugging for pete's sake. -
Problem with Runtime.getRuntime().exec
Hi ,
i'm using jBuilderX and windows 2000 server . My problem is that i can't
find why
in my code it doesn't work this:
import java.lang.*;
String command = new String("c:\\testd\\testf.bat"); // testf.bat -
batch file
Runtime.getRuntime().exec(command); // it doesn't
have any effect
Thanks in advance,What's it supposed to do?
I can definitely help you on this 1, but I'd really like to see your streamoutputs. You can get these from the Process object that is created, but you'll need to add some threaded listeners to get the data.
Is this possible? -
Unable to execute Runtime.getRuntime().exec(
Hello,
I am new to Java programming and trying to execute (OS is Linux) an external jar File with the command:
Runtime.getRuntime().exec("nohup java -jar SeismicAgents.jar &");It should start the SeismicAgents.jar and write the output to nohup.out.
This works perfectly if I just enter the command at the command line.
But upon starting it from within my program, the process seems to be started (I can see it when executin "ps aux"), but it is obviously not running as no input is written to nohup.out and the file which SeismicAgents.jar should generate is not generated.
I also tried the following code:
String cmd[] = {"nohup", "java", "-jar", "SeismicAgents.jar", "&"};
Runtime.getRuntime().exec(cmd);But I am experiencing the same problem here.
Executing something like
Runtime.getRuntime().exec(ls);works without problems...
Can anyone help?Runtime.getRuntime().exec("nohup java -jar
SeismicAgents.jar &");Java does not interprete the '&' character. Neither does
nohup. You would have to prefix this with /bin/sh -c, put
the rest in quotes and, most importantly, redirect input
and output somewhere. Without redirection, it is the task
of your java program to feed the subprocess with input
and drain its stdout and stderr buffers.
Executing something like
Runtime.getRuntime().exec(ls);works without problems...It is hard to believe this. Either it should be "ls" or
ls is string variable containing the relevant string,
but even then I would be surprised if you see any
output on the command line. At least I don't get
anything with public class bla {
public static void main(String[] argv) throws Exception {
Runtime.getRuntime().exec("ls");
}If you don't want a "/bin/sh -c" hack, you may want to
try http://www.ebi.ac.uk/~kirsch/monq-doc/monq/stuff/Exec.html .
Harald. -
Runtime.getRuntime().exec() unix shell
When I try to run commands like Runtime.getRuntime().exec("ls *")
I got null returned buffer
If I use commands like Runtime.getRuntime().exec("ls file.dat")
i got the right details
Anybody know why it happens???
ThanksInput-output redirection, filename wild-card-expansion, metacharacter evaluation etc. are performed by the command shell.
You should try String [] {"sh","-c","ls","*"} -
In cursor i have two queries where put the condition and how to print the d
hi i have 2 tables 1 is emp(empid,empname,dept,grade)
2 is salary(grade,salary)
in cursor when ever grade is increased salary automatically increased
in 2 diffrent queries where i will put the if condition and how to print the output.
any one can please suggest me.
finally my required out put is
empid,empname,grade,salary
thanksIt is always helpful to provide the following:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details. -
Runtime.getRuntime.exec() may hang?
Hi, I am trying to run a Microsoft application, suspend.exe, under Java, on xp. I noticed that sometimes the program would hang, after issuing the command.
String command = "cmd /c suspend.exe -n 15 -s 3 -l c:\\scpt\\s3.txt -e " ;
suspend = Runtime.getRuntime().exec (command);
Is there a compatibility between MS and Java after Java releases the control to the native environment? Has anyone seen this? Sometimes this gets kicked off, and sometimes it doesn't.
* I am really confused. Thanks for any helpthank you, I will look into this.
Btw, do you know how to start a java program at start up? I have searched and read some articles, but none seems to do the trick for me.
I have:
1) create a bat file. This bat file runs fine w/ double clicking, but when trying to place it in startup folder and run it, it quits.
2) create a simple c vesion of .exe file. This possesses the same behavior as above
3) create a short cut to the bat file and place it in startup folder. Nothing happens.
4) add reg. key in regedit with
'java Pclient'
and
'java c:\scpt\Pclient'
nothing seems to happen.
still searching...
thank you. -
Runtime.getRuntime().exec and quoted strings?
Attempting to execute a command containing a quoted string. Being very new to Java I'm guessing I'm not doing it right. Below are two code bits the first one works the second doesn't. So the question is "How do I use quoted strings in a command with .exec?"
// this one works
try {
p = Runtime.getRuntime().exec("ls -l tst.java");
p.waitFor();
System.out.println("Done!");
catch(Throwable e) {
system.out.println("Errors!");
// this one fails
try {
p = Runtime.getRuntime().exec("ls -l \"tst.java\"");
p.waitFor();
System.out.println("Done!");
catch(Throwable e) {
system.out.println("Errors!");I don't know if it is too late for the answer, but I think I know what the problem is.
You are using exec(String) method, and passed String parameter is parsed using StringTokenizer class. This means that when you use quotes as in "file1 file2", StringTokenizer parses this as "file1 and then file2" so it is not understandable command.
To solve the problem, do not use exec(String) method, use exec(String[])
Using this you can send separate command and separate parameters as in following example:
If you want to send (in Unix)
grep "SHOW lotid" text.txt
(using exec("grep \"SHOW lotid\" text.txt") would not work)
Do the following
exec(new String[]{"grep", "SHOW lotid", "text.txt"});
This avoids parsing problem when quotes are used.
Mehmed -
A Java SP that executes OS commands runs fine in 8.1.6, but doesn't run in
8.1.7 when a window is generated as a result of the call. The Java class
follows:
package com.crtinc.oracle.util.osrun;
import java.io.*;
public class SimpleRunner extends Object {
//just run the daggone command, don't worry about any errors, feedback,
etc...
public static void run(String cmd) throws IOException {
Runtime.getRuntime().exec(cmd);
The call spec follows:
CREATE OR REPLACE PACKAGE SIMPLERUNNER AUTHID CURRENT_USER AS
PROCEDURE RUN ("cmd" IN VARCHAR2)
AS LANGUAGE JAVA
NAME 'com.crtinc.oracle.util.osrun.SimpleRunner.run(java.lang.String)';
END SIMPLERUNNER;
When deployed to v8.1.6 by a user with JAVASYSPRIV, the following call from
SQL*Plus runs and displays a window:
exec simplerunner.run('notepad.exe');
When deployed to v8.1.7, the same call causes notepad.exe to be added to the NT
Task Manager Processes tab, but the notepad window doesn't actually open up.
FWIW, the above code is a simple example - myactual utility captures the
output streams of OS commands, very much along the lines of sample code that
I've seen on Metalink - this also works fine in 8.1.6, but never returns in
8.1.7.
Granted, running Notepad is of limited utility (though it demos very well :-),
but other useful OS commands that spawna window (such as kicking of an Oracle
Report, which pops up a small status window) do not run now in 8.1.7. Running
a completely non-visual process seemsto work fine, however.
Any help much appreciated!
Thanks
JimWell, just for anyone who might be facing such an issue in the future...
I am running the databse on NT and it turns out that my NT service didn't have the 'Allow Service to Interact with Desktop' checkbox selected, so that's why OS commands that generated windows weren't showing up. Checking that checkbox and stopping/restarting the service solved the problem.
Jim
null -
Hi,
I am trying to launch an application 4 times with different arguments from a Java app. I have tried doing it sequentially and in four different threads, but the results are the same: sometimes the 4 of them are properly launched, sometimes (the most of the times) only 3 are launched and sometimes only 2. I have tried with cmd and cmdarray[] as parameters for exec but the results are the same.
This is one of the four threads I use:
Runnable r1 = new Runnable(){
public void run(){
String ecgCommand = "./flute -S -m:" + Config.ECGS_FLUTE_IP + " -p:" + Config.ECGS_FLUTE_PORT + " -F:" + Config.ECGS + " -r:" + Config.ECGS_FLUTE_RATE + " -C";
System.out.println(ecgCommand);
InputStream ecgsStream = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
ecgsProcess = Runtime.getRuntime().exec(ecgCommand, null, new File(Config.HOME_PATH + Config.FLUTE_PATH));
String line;
ecgsStream = ecgsProcess.getInputStream();
isr = new InputStreamReader(ecgsStream);
br = new BufferedReader(isr);
StyledDocument styleDoc = mm.ecgFluteMessages.getStyledDocument();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
while((line = br.readLine()) != null && running){
if(styleDoc.getLength() > 25000) mm.ecgFluteMessages.setText("");
styleDoc.insertString(styleDoc.getLength(), line+ "\n", def);
mm.ecgFluteMessages.setCaretPosition(mm.ecgFluteMessages.getDocument().getLength());
System.out.println(ecgsProcess.waitFor());
}catch(Exception e){
try {
br.close();
isr.close();
ecgsStream.close();
} catch (Exception e1) {
e.printStackTrace();
new Thread(r1).start();Adding a Thread.sleep between runnables doesn't have any effect.
In addition, those processes that are not properly launched return an exit value of 255. I have searched for its meaning but I have found nothing. Could anybody tell me where can I find a list of the JVM exit codes in order to guess what is happening?
Can anybody help me with this issue? Help is much appreciated.
Thanks a lotI have been looking for it but it seems it has not any exit code list or any documentation regarding this. Anyway, I think 255 is a JVM error code (the last one, errors are numbered in modulo 256) which means that the error has nothing to do with JVM but with the application execution (flute in my case).
I have added a prompt for the errorStream and I have this message for the 255 exited programs:
not well-formed (invalid token) at line 15+
And the four commands are like this:
*./flute -S -m:239.255.255.253 -p:60102 -F:./ecgs -r:150 -C*
*./flute -S -m:239.255.255.252 -p:60103 -F:./ads -r:150 -C*
*./flute -S -m:239.255.255.251 -p:60104 -F:./pushvod -r:50 -C*
*./flute -S -m:239.255.255.250 -p:60105 -F:./banners -r:150 -C*
So, as the process is sometimes initialized properly and others it is not, it seems that there is a problem with the tokenizing of the command not happening always. As I have tried it with a single command line and with an array of command strings (the first for "./flute" and the followings for each argument) with the same results I can't understand why is this problem happening sometimes. Happening always would help me in giving a clue but that's not the case.
Any idea? Thanks a lot.
Edited by: dulceangustia on Apr 3, 2008 3:41 AM
Maybe you are looking for
-
Update from Oracle 11.1.0.6.0 to 11.2.0.3
Hi, I have Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production installed on red hat server. I want to update it to oracle 11.2.0.3. Please suggest steps to be followed. Thanks Nitin
-
Performance Tuning on a table where WHERE clause is having only PK columns
Hi folks!! Here is the gotcha!!!! I am having a table, named X, with primary key columns A and B. I running a packaged procedure in which there is a SELECT statment to get the record from the table X with WHERE condition on A and B columns. Now the p
-
Good day. I have a WebDynpro component which executes a BAPI in backend. Which names of the RFC objects to be protected should I enter? I have entered the following PRGN_G2EE, RFC1, SDIFRUNTIME, SYST, SYSU... But now it says that "User XXX has no RFC
-
i cant update my iphone 4s ios 6.1.3 to ios 7 he gave me a message ( an error occured downloading ios 7
-
Crashes at Launch, after Mac Virus
I got a virus on a mac and apple tech support had me erase many folders and files from my hard drive in order to remove all races of the virus. Ever since that, AI crashes without fail every time I launch and try to open a file or start a new documen