Why is Runtime.Exec not perfekct?
Hi!
I need to execute a program from java using Runtime.Exec(). I have done everything right with redirection the output stream and read it from a seperate thread. This works for most of the programs I tried, but not for all. Sometimes I miss some of the output.
But if I use redirection to a file from the shell it works perfect.
(i.e. /bin/pramsim > outfil)
Why is this? Why isn't Runtime.exec as good as shell redirection?
/Karl
Ok sorry, here is some more detalis.
The program( pramsim) prints to both standard output and standard error. Output written to stderr does always work. But output so stout fails quite often. After some research I found out that pramsim is using the function printf(...) which is bufferd by default. So I only get the output when the program prints alot, so the buffer gets full.
Can I in some way turn buffering off from java? Found a C function called setbuf(1,null) which turns buffering off. But this means I have to changes the code to pramsim, and I want to avoid that!
I also wonder: How does redirection in the shell make this work. I guess buffering is turned off when I redirect to a file using 'pramsim > outfil'. (maybe this is more a C question but I hope that I can get some help here)
/Karl
Similar Messages
-
Runtime.exec not executing the command !
Hi all,
I'm connecting to Progress Db thru JDBC trying to execute a stored procedure
which has a statement
Runtime.exec("ksh -c aa") where aa is aunix script which i'm trying to run from java snippet .
when i run this code as a seperate java program it executes the script
"aa" but thru JDBC connection it does not execute the command
what could be the reason ???
thanx in advance,
Nagu.Hi Rick,
"aa" is the shell script which is lying in the user DIR .
It is returning a non-zero value. what kind of permissions be there for to execute the Shell command?
Regards,
Nagarathna. -
Runtime.exec not releasing lock on files
Hi,
I am using Runtime.exec to launch an external application, a batch file that runs a java program and generates a pdf file on disk. The Runtime.exec is called from inside the callback function of a toolbar button in my UI. Once, the runtime.exec returns, I popup a alert saying "pdf generated successfully". However, when I try to open the pdf that has been generated, I get a message saying the "program is in use by another program" or some such message. Only when I quit my GUI application, Iam able to open the pdf file using acrobat reader.
Can someone tell me how to solve this problem. I have tried doing proc.waitFor() etc.
Cheers,
vidyutYou can try some of sysinternals tools to look through file sharing information and decide what process is locked file.
PS Try to ensure that you start java in same process as batch file executes, overthise you just can't ensure it terminates on time. -
Why runtime.exec() not working?
I just want to run "ls" i unix on my JSPs.
Process process;
Runtime rt = Runtime.getRuntime();
String line;
process = rt.exec("ls");
Here's the error message.
java.io.IOException: ls: not foundOn my Linux
rt.exec("ls");
does work.
If, on your system,
which ls
does not return an external executable like /bin/sl, try this command line:
import java.io.*;
public class Ls{
public static void main(String[] args){
String line = null;
try{
Runtime rt = Runtime.getRuntime();
Process prc = rt.exec(new String[]{"sh", "-c", "ls"});
InputStream is = prc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while((line = br.readLine()) != null){
System.out.println(line);
prc.waitFor();
catch (Exception e){
e.printStackTrace();
} -
Difference between command line and Runtime.exec()
Hi all.
I'm coding some lines to call sqlldr program.
System info:
OS: Win2k server
Java platform: JSK 1.4
DBMS: Oracle 9i
I've tested sqlldr in command line and it is OK. But when i call Runtime.exec("sqlldr user/pass@servicename control=mycontrol.ctl")
the ErrorStream show that: Message 2100 not found,No message file for product=RDBMS ,facility=UL...
So i had to put a String array which contained "ORACLE_HOME" as the second parameter of exec method. But there's another error appear:
SQL*Loader-704: Internal error: ulconnect: OCIServerAttach [0]
ORA-12560: TNS:protocol adapter error
I checked tnsnames.ora and it's OK. I do the command line again and it's still OK. Why did Runtime.exec("...") method get Error.
Does Someone solve it for me.
Thanks so much.I'm having the similar/same issue.
I'm trying to run SQLLdr from JAVA.
From a command line, it works fine.. From within JAVA, I get..
SQL*Loader-704: Internal error: ulconnect: OCIServerAttach [0]
ORA-12640: Authentication adapter initialization failed.
Did you find a solution to your problem? -
Problem in Runtime.exec()
I am trying to launch a new java application from my java program like this-:
import java.io.*;
public class test123{
//String userStr="";
public static void main(String args[]) throws Exception{
Process p = Runtime.getRuntime().exec("java JavaExec",null,currentDir);
Thread.sleep(10000);
System.out.println("After Destroy");
} The JavaExec file�s code is -:
import java.io.*;
import org.apache.log4j.Logger;
public class JavaExec
static Logger logger = Logger.getLogger("JavaExec.class");
public static void main(String args[])
try
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("notepad");
int exitCode=0;
while(true)
//logger.info("Inside the infinite while loop in javaexec");
try
exitCode = process.exitValue();
System.out.println(exitCode);
process.destroy();
process = runtime.exec("notepad");
catch(IllegalThreadStateException itse)
System.out.println("Inside exception");
} catch (Throwable t)
t.printStackTrace();
}Notepad opens when I execute the test123 class but instead of remaining open even if I close it , I am able to close notepad. The JavaExec only starts processing again when my main quits.
Please let me know the solution to this problem.....
Thanks in Advance
Inder Jeet SinghConvoluted at best. You don't need that loop, just useexitCode = process.exitValue();and it will block until notepad exits.
P.S. Why a Runtime.exec() executing a Java program that does a Runtime.exec() on notepad? -
Runtime.exec with spaces not working EVEN using String[]!!
Hi everyone,
I need to start the rmi registry from some code,and i need to pass it the classpath of two jars when initialising it. My problem is that the paths I set aren't taken when they contain a space.
Here's the code:
<code>
String rmiRegistryCommandLine[] = new String[] {
+ System.getProperty("java.home")
+ "\\bin\\rmiregistry.exe\"",
"-J-Djava.class.path=\""+System.getProperty("user.dir")+"\\MyJar.jar\"",
"1099"};
Runtime.getRuntime().exec(rmiRegistryCommandLine);
</code>
I know that Runtime.exec(String) tokenizes the input, which is why I'm not using it, but Runtime.exec(String[]) isn't supposed to tokenize the input. System.getProperty("user.dir") can contain a space, so I put quotes around that, but I need the -J-Djava.class.path in the same string. I tried breaking it up into two more separate strings but it didn't even run for normal non-space paths then. I am sure that if the whole -J-Dblah....upto MyJar.jar was in quotes then it would work, but I need the classpath in quotes separately as it could contain a space.
Can anyone help me get this working?Ya, that's fine but the command line I want to pass is:
d:\j2sdk1.4.0\bin\rmiregistry.exe -J-Djava.class.path=d:\my dir with spaces\MyJar.jar;d:\my more dir with spaces\MyJar2.jar 1099
If I say
arg[0]="d:\\j2sdk1.4.0\\bin\rmiregistry.exe";, that's finebut arg[1] is the problem
if I say
arg[1]="-J-Djava.class.path=d:\\my dir with spaces\MyJar.jar; d:\\my more dir with spaces\\MyJar2.jar";, then it definitely won't work on 9X machines and probably not on NT.
if I break up arg[1] into:
arg[1]="-J-Djava.class.path=";
arg[2]="d:\\my dir with spaces\\MyJar.jar";
arg[3]=";";
arg[4]="d:\\my more dir with spaces\\MyJar2.jar";I'll need to put quotes around the two individual two class paths or else it won't work.
I find though that if I put the classpath as follows
d:\"my dir with spaces"\MyJar.jar then it seems to work.
I think a regular expression function to search for any directory with spacees and then put quotes around it and reinsert it into the path would be the solution. -
Runtime.exec() is not parsing properly when a argument contains space
Hi,
Runtime.exec("a.exe hai \"how r u\"); to execute a sample application...
In windows the argument received by a.exe are as follows:
hai
how r u (as a single argument)
In Solaris the argument received by a.out are as follows:
hai
"how
r
u"
Why it's happening this way??
using jdk1.5_08
Note: using processbuilder is not possible as of now..
Thanks.folks thanks for your reply..
But I think will not solve my problem. These things
will surely work, but our customer have this running
in the their work place and facing this problem only
in solaris and not in windows.. so we can fix this in
the next release.. but want could be the solution now
!You could prefix the command with "sh -c " so that the shell is active once again but on some shells this does not work. Must be worth a try.
>
We need to give a reply to them, saying whether it is
our bug or a problem in Java API since it's working
fine in Windows.Behind the scenes, Windows (or really DOS) has created frigged version of the Unix 'C' exec() calls library so that they behave similar but not the same a the Unix version. I suspect Java just uses this library.
>
Question : Why passing whole command with argument as
a single works in windows and not in solaris/unix ?
Can I conclude and say this is due to a bug in Java
API?Definitely NOT.
Edit : I have been racking my brains and I think you need the command string to be
"sh -c \"YourExecutable hai \"how r u\"\""
because the -c option says treat the next argument as a command to the shell.
Message was edited by:
sabre150 -
Runtime.exec() works in Win98 but not in XP?
Hi all!
I have the following problem: I am using following lines of code in win98 to launch a MSDOS-window from my application (with some arguments to it):
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("start "+"command.com"+"/k"+"java -cp \""
+getArgument(directory,false)
+"\""+" "+getNoExtent(file));
proc.waitFor();
catch (Exception ex) {
ex.printStackTrace();
This works very well, however in XP it doesnt do a thing (I know that I have to change 'command.com' to 'cmd' or 'cmd.exe'). I have already tried that but it wont work. Instead, this exception occurs while running on XP:
java.io.IOException: CreateProcess: start cmd error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:566)
at java.lang.Runtime.exec(Runtime.java:428)
at java.lang.Runtime.exec(Runtime.java:364)
at java.lang.Runtime.exec(Runtime.java:326)
at JSEdit.actionPerformed(JSEdit.java:443)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
64)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
ctButton.java:1817)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
.java:419)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
at javax.swing.AbstractButton.doClick(AbstractButton.java:289)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1
113)
at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mouseRelease
d(BasicMenuItemUI.java:943)
at java.awt.Component.processMouseEvent(Component.java:5134)
at java.awt.Component.processEvent(Component.java:4931)
at java.awt.Container.processEvent(Container.java:1566)
at java.awt.Component.dispatchEventImpl(Component.java:3639)
at java.awt.Container.dispatchEventImpl(Container.java:1623)
at java.awt.Component.dispatchEvent(Component.java:3480)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
at java.awt.Container.dispatchEventImpl(Container.java:1609)
at java.awt.Window.dispatchEventImpl(Window.java:1590)
at java.awt.Component.dispatchEvent(Component.java:3480)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:197)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
What should I do?
Thanx!
Regards
VeroslavCheck you string concatenation, you're missing spaces or you are not providing the actual code:
Process proc = rt.exec("start "+"command.com"+"/k"+"java -cp \""
+getArgument(directory,false)
+"\""+" "+getNoExtent(file));Let's dissect:
String command = "start ";
// command := "start "
command += "command.com";
// command := "start command.com"
command += "/k"+"java -cp \""
// command := "start command.com/kjava -cp\""You can always trace these kind of errors by using a debugger. Or dump the string you are passing to System.out. Every comprehensive IDE has a debugger built in, or you can resort to jdb.
Greets
Dhek Bhun. -
I have developed a program which uses Runtime.exec(). It works in development but not in the production.
The development machine runs Windows2000 with SDK 1.4.0.
This program does not run on the target machine (production). The target machine is a Windows2000 servers with JRE 1.4.1_01.
Here is the error:
java.io.IOException: CreateProcess:
"C:\Program Files\2TIFF\2TIFF.EXE"
"s=C:\SplitTiff\pet.tif"
"d=D:\SplitTiffWork"
-namegen=123456.tif
-sep
-ct3
error=3
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Unknown Source)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at utility.splitTiff.SplitTiff.extract(SplitTiff.java:54)
at utility.splitTiff.SplitTiff.main(SplitTiff.java:340)
The six lines following "Create Process:" are the elements of the String[] parm of Runtime.exec().
Error 3 was returned by the JRE.
Does anyone have any suggestions what is going on?
Thanks much! I've got some Dukes to give out for some help on this.
Bill BlalockThanks!
Where can I find out the meaning of errors returned by Runtime.exec()?
Please reply to
http://forum.java.sun.com/thread.jsp?forum=54&thread=291993
And I'll send a couple a Duke I have locked up over there your way.
Have a good weekend!!! -
Runtime.exec() in Java not working in Oracle 10 Application Server
Hi ,
I am trying to call a .exe file which is in the Web Application folder .
I am Using Process p = Runtime.exec("path to .exe file ")
This code is working fine when used with JBOSS , but not working with Oracle Application server .
Please tell me whether i need to do any chnages to make it work
Thanks in advance .I ran a quick test with your code, I just had to make some small changes, and things work for me...
I'm testing with JDeveloper 10g 10.1.3.2.0 ...
The only thing I wonder is DBUser DBPass DBHost, those are not the actual values, correct?, neither they are environment variables?...
In the server hosting your OAS, you should try running the whole CMD line from the start/run dialog ... make sure it works in that server ...
Here is the code used in my test:
In JSP:
<%@ page import="runexepkg.*" %>
<%
String msg = "";
try
RunEXE p = new RunEXE();
msg = p.main1();
catch(Throwable t)
System.out.println("Exception Raised");
t.printStackTrace();
%>
<%= msg %>In Java Class:
package runexepkg;
import java.sql.*;
public class RunEXE
String ss="";
public String main1()
try
Runtime rt=Runtime.getRuntime();
Process p = rt.exec("CMD /C start C:\\oraappserver\\j2ee\\WebGis\\applications\\PowerGis\\web\\WEB-INF\\classes\\GisProject\\cust_data_1.exe DBUser DBPass DBHost");
System.out.println("Command has been executed");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@DBHost:DBPort:orcl","DBUser","DBPass");
System.out.println("Test Connection ========== "+con);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT SYSDATE FROM DUAL");
if(rs.next())
ss="Command has been executed - Database has been accessed";
else
ss="Command has been executed - Database was not accessed";
catch(Throwable t)
System.out.println("Exception raised, command has NOT been executed");
ss="Exception raised, command has NOT been executed";
t.printStackTrace();
return ss;
}Edited by: Rodolfo Ferrari on Jul 23, 2009 10:40 PM -
my servlet calling the above line is not executing to make a directory
"abcd" at specified location. i am using Mandrake Linux and Tomcat... can anybody expalin the error.Hi raghutv,
I also have this error
I use Tomcat 4.0 and Window Me
Do u think that the problem is "Window OS" or Tomcat Setting
I have a problem. I want to complie the other Java Program "hi.java" using servlet.
I am compiling the servlet code succesfully, but the web page can't display anything.
The real path of "hi.java" is in the
D:\Program Files\Apache Tomcat 4.0\FYP\WEB-INF\classes\hi.java
This is my servlet code..............pls help.............thx!
/*********************** Hello.java *********************/
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet
public void service(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
try {
String path = getServletContext().getRealPath("\\WEB-INF\\classes\\hi.java");
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("javac.exe " + path);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
PrintWriter com_out = res.getWriter();
com_out.println("<pre>");
String line = null;
while((line = br.readLine()) != null){
com_out.println(line);
//String[] cmd = { "ping.exe", "time.nist.gov" }; // Command and argument
//String[] cmd = { "javac.exe","hi.java"}; // Command and argument
//Process process = Runtime.getRuntime().exec(cmd); // Execute command
//Process process = Runtime.exec(cmd); // Execute command
//process.waitFor(); // Wait until process has terminated
catch (Exception e) {
System.err.println(e); -
Runtime.exec() does not work normally
I try to wrapper the oracle connect command on unix using this function:
runtime.exec("sqlplus username/password@dbinstance")
it is ok on windows, but on unix, after runing the class, I get nothing. what is the problem?
Please help me. thanksThere are several traps with runtime.exec(). The most important one is that you should read
the output stream of the launched program. Otherwise it will stop running when the console buffer overflows. The size of the buffer differs for various OSes.
Look at this article:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
It it does not answer your problem, try to search the forums:
http://search.java.sun.com/Search/java?qt=%2B%22exec%22+-%22Replies%3A+0%22&col=javafrm&rf=0&qp=%2Bforum%3A31
This problem has been asked hundreds of times.
Hope, this helps. -
Runtime.getRuntime.exec() not working with through Servlet
Hi ,
I want to open a IE from servlet,I am using a Runtime.getRuntime.exec to open the browser ,but my servlet is executing but IE is not opening...Here i am using TomcatServer...Is any settings to be Done in TomcatServer.
My Servlet code is
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
String s1 = "C:/Program Files/Internet Explorer/IEXPLORE.EXE";
String s2 = "http://192.168.0.149:8080/etk/etk3.htm";
Runtime runtime = Runtime.getRuntime();
runtime.exec(s1 + " " + s2);
i know it is contrary to the purpose servlets are meant for.but i am using for different purpose..
help me on this one...
Thanks in AdvanceNo, I am using the right path, I am sure. Also I tried giving the absolute path of the UserGuide.pdf. Still it cannot find. Please anyone try spawning an application from a different directory and lemme know your openion.
Regards,
Thomas. -
Runtime.exec() does not work under Linux
Hi,
I have a generic application runner class that runs an external
program and redirects stdout/stderr to a buffer/file.
While everythings works just fine under Windows, I get the
following exception under Linux trying to run the Java interpreter
'java':
java.io.IOException: "/usr/lib/SunJava2-1.3.1/jre/bin/java": not found
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:139)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:546)
at java.lang.Runtime.exec(Runtime.java:413)
I have checked that the file /usr/lib/SunJava2-1.3.1/jre/bin/java
exists.
Any help appreciated!
Marccan I ask how you solved it? I am having a problem
with quotes just now to and it might help me!I simply tested what the current platform is and
only used quotes under Windows.
Marc
Maybe you are looking for
-
hello all, i have a two tables called item and order, and i have a form on order. the table item is having itemid & itemname the table order is having orderid, itemid & qty in the order form when the user executes the query the data has to be display
-
Returning only records that have no entry in a specific field
Hello, I'm new to this forum and relatively new to Crystal Reports, so I apologize if this information is "plain as day" somewhere. I've been hunting for this info for quite a while and can't find anything that makes sense! I am trying to put togeth
-
ORA-06503: Function returned without value at WWV_FLOW_WEBSERVICES_API
Hi, I use APEX_WEB_SERVICE.MAKE_REQUEST function to call web service however stuck with ORA-06503 exception. It would be nice to hear comment from someone who knows APEX_WEB_SERVICE from inside. ORA-06503: PL/SQL: Function returned without value ORA-
-
Why can't apstore find the apps I am searching for?
This happens to me all the time. I search for Instagram and get a lot of apps but not Instagram. I wanted Omni, the search engine said it did not exist. To find the apps I had to go to the developer's sites and find a downloadlink - and then download
-
Mail 5.0: No Sound Effects
Hello! Since installing Lion, Mail 5.0 keeps dropping it's sound effects. They come back for a short while once I "repair disk permissions" (only works with Mail closed down). All sound boxes are checked. Anyone have a perminant fix? If not, any id