Runtime.exec() under Linux
My game's installer works on windows and mac but on linux it's getting this error:
java.io.IOException: Cannot run program "javaw": java.io.IOException: error=2, No such file or directory
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
Here's my code:
public void runProgram(){
String dir = folder;
if(os_type == LINUX && dir.charAt(0) != '/'){
dir = "/"+dir;
File file = new File(dir+"SFC_Updater.jar");
if(file.isFile() == false){
System.err.println("Could not find updater jar: "+file.getPath());
throw new RuntimeException();
if(os_type == LINUX){
System.err.println("Attempting to run with special linux arguments because linux is SPECIAL!");
String[] args = new String[4];
args[0] = "javaw";
args[1] = "-jar";
args[2] = "\""+dir+"SFC_Updater.jar\"";
args[3] = dir;
try{
Runtime.getRuntime().exec(args);
catch(Exception e){
System.err.println("Linux Fails.");
e.printStackTrace();
else{
try{
Runtime.getRuntime().exec("javaw -jar \""+dir+"SFC_Updater.jar\" "+dir);
catch(Exception e){
e.printStackTrace();
}Thanks
Have you tried including the full path for javaw in
the Linux version?It is interesting to note that the Linux version does not have a javaw
Similar Messages
-
Hi
I am trying run this peace of code under linux System
String c="/usr/java/jdk1.6.0_02/bin/java -jar \"/root/JavaApplication1/dist/JavaApplication1.jar\" \"a\" \"b\" \"c\"" ;
try {
Process p=Runtime.getRuntime().exec(c);
} catch (IOException ex) {
ex.printStackTrace();
}JavaApplication1.jar should display a frame
but I do not have any thing
and the exit code of the process is 0
how can I fix this
any help
regardsHave you tried including the full path for javaw in
the Linux version?It is interesting to note that the Linux version does not have a javaw -
How to make Runtime.exec call Linux exec?
Howdy,
I am trying to use a combination of 'find' and 'rm' to delete all files with a certain extension in a directory and all of its subdirs.
Here's the command:
Process proc = runtime.exec("find " + dir + " -name '*.vcs' -exec rm -rf {} \\;");
It's failing, not sure why, the exitCode is 1 instead of 0. I'm not sure if it's because I have to escape the '\' character, or if it's because I am calling Linux's 'exec' function within a Java exec() call, or something else entirely.
The easiest thing to do would be to just use rm, but that doesn't seem to be an option. With rm it seems to be all or nothing -- If I try:
rm -rf *.vcs
it fails if it doesn't find a file with that extension in the start directory (even though I've specified -r). But if I enter:
rm -rf *
it nukes my directories AND files, something I don't want to happen. I realize this is a Linux thing, I'm just explaining it here as background, just in case.
Anyway, so is there a way to do this? Perhaps with another system call, without using Linux's exec()?
Many thanks
Bobimport java.io.*;
public class ExecutingALinuxCommand
static class PipeInputStreamToOutputStream implements Runnable
PipeInputStreamToOutputStream(InputStream is, OutputStream os)
is_ = is;
os_ = os;
public void run()
try
byte[] buffer = new byte[1024];
for(int count = 0; (count = is_.read(buffer)) >= 0;)
os_.write(buffer, 0, count);
catch (IOException e)
e.printStackTrace();
private final InputStream is_;
private final OutputStream os_;
public static void main(String[] args)
try
String dir = System.getProperty("user.home") + "/work/dev";
String[] command = {"sh","-c", "find " + dir + " -name '*.java' -exec grep -l Runtime {} \\;"};
final Process process = Runtime.getRuntime().exec(command);
new Thread(new PipeInputStreamToOutputStream(process.getInputStream(), System.out)).start();
new Thread(new PipeInputStreamToOutputStream(process.getErrorStream(), System.err)).start();
int returnCode = process.waitFor();
System.out.println("Return code = " + returnCode);
catch (Exception e)
e.printStackTrace();
} -
Runtime.exec() under a specific user account ???
Hi there,
I cann't figure out how to run a script on Unix under a specific user account using the Runtime.exec(). Currently whoever run the java program, the script is ran under that user account.
The code is like:
public class javarun {
public static void main(String[] arg) {
String str = "myunixscript";
// check the arg[1] to decide the appropriate environment.
Runtime r = Runtime.getRuntime();
try {
Process pr = r.exec(str);
pr.waitFor();
int exitstatus = pr.exitValue();
} catch (...) {...}
We have two user accounts: unixusr1 and unixusr2. Now I need to have unixusr1 run the java program ( ie. unixusr1$ java javarun), while the "myunixscript" be executed under unixusr2. One further step is to the unix account name as a parameter so the unixscript could be run under different account.
Any help will be highly appreciated. Thanks.
Edward.I'm not sure if I have a solution, but here are some questions:
a) have you tried writing additional input to the OutputStream of the process? Although I have not tried it, I would imagine that Process.getOutputStream() exists for commands that require the invoking resource to send additional input to the process- like an su command that requires a password check.
b) can you just write a shell script that takes the needed information as an argument. That is, write a shell script that takes the username and password as an argument and then you can use Runtime like,
Runtime.exec("myScript", new String[] { "hisId", "hisPasswd" });Obviously, you would need to think through the security concerns of such a script, but, if it complies with the security structure of your environment, it might allow you to avoid the problem by using the shell script to invoke the destination command with the proper UID and password, rather then using the JVM to invoke it. Basically, the script becomes a proxy for the JVM to invoke that command. -
Launch Acrobat Reader with Runtime.exec() under WINNT4, without absolut pat
Hi,
I would like to launch Acrobat Reader from a Swing application. This works fine with Runtime.exec() as long as I provide the full path to the AcroRd32.exe. The problem is that I cannot predict the location of this exe on the systems of the users. Athough is in the Windows PATH, since I can launch from the windows execute-dialog, the Runtime.exec() is not able to locate the file.
How can I solve this problem?
Thanks a lot!
Horsthey BIJ, thank you so much man. start really does wonders!! i was stuck with invoking a fortran program for last couple of days and now i went through your postings and tried with start. it did work!!
thanks again,
bhairampally -
Runtime.exec() on Linux RedHat. help!!
Guys
I've having a lot of problems with Runtime.exec() across RedHat platforms.
I'm trying to execute a external process but it doesn't responds.
when I execute the 'ps' sentence the process appears, but apparently don't work.
If I run this proccess at the command line, it works fine.
Can anyone offer an help?
ThanksDon't forget that the output of the "Process" is not redirected to "System.out".
--> if you want to see the output, you'll have to get the output stream of the process and dump it yourself
InputStream processOutput = process.getOutputStream() ;
byte buffer[] = new byte[ 512 ] ;
while( true ) {
int read = processOutput.read( buffer ) ;
if( read<=0 ) {
break ;
System.out.write( buffer, 0, read ) ;
} -
Hi,
I'm having some difficulty getting Runtime.exe() to work on Linux. I was trying to run "make oldconfig" from my Java program.
public Action()
Process p = Runtime.getRuntime().exec ( "make oldconfig" );
InputStream processStream = p.getInputStream();
OutputStream commandStream = p.getOutputStream();
InputStream procErrorStream = [/getErrorStream();
p.waitFor ();
private void outputData ()
int hasInput;
if ( ( hasInput = processStream.available() ) >0 )
byte[] buffer = new byte [hasInput];
int len = processStream.read(buffer);
if ( len > 0 )
System.out.println( new String ( buffer, 0, len ) );
if ( ( hasInput = procErrorStream.available() ) >0 )
byte[] buffer = new byte [hasInput];
int len = procErrorStream.read(buffer);
if ( len > 0 )
System.out.println( new String ( buffer, 0, len ) );
}I don't see any errors from this command, but it doesn't look like the "make oldconfig" is called because I'm not seeing any outputs. Can anyone help or give me some hints to debug this? Thanks.The line
InputStream procErrorStream = [/getErrorStream();
looks a bit dodgy to me -
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 -
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 ?
-
Runtime.exec(), linux and redirection
Hi all,
I need to exec an external command from java under linux, and have both the stderr and stdout of the command redirected to the
stdout, so that I can capture them and keep them in synch in the java app. I've tried many combination, but I'm unable to make
this work: only the standard output shows up. Note that I can make this work under windows.
A java code example and a small C example to simulate the program to be invoked follows. Running the java program should show both the "messsage" and the "error" lines, but it shows only the "message" ones.
Note that removing the apparently redoundant ">&1" doesn't solve the problem. I got a suggestion to modify the exec invocation into
String[] cmd = { "/bin/sh", "-c", "./test1 >&1 2>&1" };
Process p = Runtime.getRuntime().exec(cmd); but that didn't work eiter.
Can anyone tell me where I'm wrong?
Roberto
======================= class test.java ================================================
import java.io.*;
public class test {
public static void main(String args[]) {
new test();
public test() {
try {
Process p = Runtime.getRuntime().exec("/bin/sh -c ./test1 >&1 2>&1")
InputStream inStr = p.getInputStream();
BufferedReader inBr = new BufferedReader(new InputStreamReader(inStr));
String line;
while((line = inBr.readLine()) != null) {
System.out.println("line = "+line);
try {
p.waitFor();
} catch(InterruptedException ex) {}
System.out.println("process terminated with code = "+p.exitValue());
inBr.close();
}catch(IOException ex) {
System.out.println("IOException : "+ex.getMessage ());
}======================= end of class test.java ================================================
======================= test1 program ================================================
#include <stdio.h>
int main(int argc, char **argv) {
int i;
for(i=0; i<100; i++) {
fprintf(stdout, "message %d\n", i);
fprintf(stderr, "error %d\n", i);
}======================= end of test1 program ================================================Redirection dosen't work with Runtime.exec(), it really dosen't have sense. Do the foolowing:
String[] cmd = { "/bin/sh", "-c", "./test1" };
Process p = Runtime.getRuntime().exec(cmd);
OutputStream out = p.getOutputStream();
//now wrte out to the file, formating as you want
What is doene obove is execute your command, without redirection, and the obtaininh the output stream of the created process. This is "the place" where the process will write everithig it'll would write in the console if executed there.
The handle the OutputStream as any other OutputStream, and write it to the HD or do whtever you want.
Abraham. -
Using Runtime. exec() copying files from folder1 to folder2 using cp command in Linux. It will take each file copy 2 sec if we use web logic 10.3 and jrocket. if we run in Linux without web logic it takes only 0.013 sec. why it takes more time to load cp command with web logic.
Environment
Weblogic 10.3
Linux 5.2
Jrocket 1.6A 64 bit VM is not necessarily faster than a 32 bit one. I remember at least on suggestion that it could be slower.
Make sure you use the -server option.
As a guess IBM isn't necessarily a slouch when it comes to Java. It might simply be that their VM was faster. Could have used a different dom library as well.
Could be an environment problem of course.
Profiling the application and the machine as well might provide information. -
Runtime.exec() on RedHat Linux
Guys
Like many before me, it seems, I've having a nightmare with Runtime.exec() across platforms when executing local files.
I've gone for the basic but robust strategy of writing the required function to a local file and then executing the file. This has worked fine on Windows NT/2000 and on Solaris. But RedHat Linux doesn't want to know.
I know my permissions are good to execute. I can create the file then run it at the command line, but then whenever I go to run from within Java I get an exit value of 255.
An old chestnut, I know. But can anyone offer an help?
Cheers
DomHere's a small class & main method that illustrates the problem.
The output I get is:
File path: /tmp/Temp26345.sh
chmod +x exit value: 0
Executing file: 255
I can then go into /tmp and run ./Temp26345.sh at the command line and get the "ls" command to run.
import java.io.*;
public class FileExecutor
public static void main( String[] args )
if( args.length == 0 )
System.out.println("Arguments must be given: [filename] [writeable]");
return;
try
FileExecutor fe = new FileExecutor();
File executable = fe.createFile( args[0] , args[1] );
fe.executeFile( executable );
catch( Throwable t )
t.printStackTrace();
public File createFile( String fileName , String contents )
throws IOException
//Create the file.
File tempFile = File.createTempFile( fileName , ".sh" );
//Write to the file.
FileOutputStream fos = new FileOutputStream( tempFile );
OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" );
int length = contents.length();
osw.write( contents , 0 , length );
osw.flush();
osw.close();
fos.close();
return tempFile;
public void executeFile( File file )
throws InterruptedException , IOException
String filePath = file.getAbsolutePath();
System.out.println( "File path: " + filePath );
Runtime runtime = Runtime.getRuntime();
//Actual system permission.
Process process_perm = runtime.exec( "chmod +x " + filePath );
int exitValue = process_perm.waitFor();
System.out.println( "chmod +x exit value: " + exitValue );
//Execute the file.
Process process_exec = runtime.exec( filePath );
exitValue = process_exec.waitFor();
System.out.println( "Executing file: " + exitValue ); -
Runtime.exec() problem with Linux
Hi All,
I have a java program which I am using to launch java programs on all platforms.
I am using the Runtime.exec() method to start the process in a separate JVM.
But, I had a problem with the -classpath switch if the directories contained spaces. So I modified the java command which I am passing to the exec() method to something like:
java -classpath \"./my dir with spaces\" com.harshal.MainThis I had to do because of the problem in windows. But, if I use double quotes in Linux (for the classpath switch in my exec() method), it won't work.
Can anyone correct me so that I can use the Runtime.exec() method on all platforms to launch the java application even if the classpath directories contains spaces.
Thank you very much.I was reading about the command line args on java's
tutorial and I found a shocking news. Mac OS doesn't
support command line args, That's news to me. Could you please elaborate ?
More important is: I got it working. I figured out I had forgotten to try something before, or, to be more correct, I made an error when trying malcommc's envp suggestion: I used "classpath" as key, not "CLASSPATH", as it should have been.
Ran a new test, got it working.
Sample:
Given a rootdir. Subdirectory "cp test" with a classfile (named "test") without package declaration. Running another class in another directory, using:
String[] cmd = new String[]{
"java", "test"
String[] envp = new String[]{
"CLASSPATH=rootdir:rootdir/cp test" // <-- without quotes.
Runtime.getRuntime().exec(cmd, envp);It's been my wrong all the time. I didn't check hard enough. It simply had to work somehow (that's the kind of things that's easy to say afterwards :-)). -
Runtime exec problem to execute a C program
Hi,
I've spend lot of time trying to find a solution without success...
My aim is to run a C program from a java application under linux. My C code is the following:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
main(int argc, char **argv){
printf("hello world \n");
Once compiled I run my java application wich run the binary through a runtime.exec().
I followed the example given by
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
with the same input gobblers and threads.
For some reason it doesn't work: nothing comes out...
When I call "ls" instead of my binary it works perfectly!
WHY??
Any help would be greatly appreciated!Thanks for the reply.
Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
The executables I want to execute from my java application don't need any arguments.
If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
cheers -
Using redirection operator ( ) in Runtime.exec()
I am trying to execute a command "cat abc.txt > 123.log" from my Java program using Runtime.exec(). However, the exec() command isnt able to interpret ">" as an operator, instead it uses this as a string. Any suggestions on how I can run the above command using exec()???
hi hiwa,
could u tell me, why dont this
e, why dont this program is not clearing the screen
in linux. though some commands are working like
"poweroff", "reboot"..
public class ExecuteCommand{
public static void main(String[] args) throws
ws Exception{
String[] cmd = {"sh","-c","clear"};
//String cmd = "clear";
Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
Commands like "poweroff" and "reboot" work on underlying system while "clear", "cd" etc.
work on current shell. Current shell is the shell on which we have invoked java command.
But the shell java runtime invokes is not(can't be) current shell but its child, a sub-process.
Thus we don't see current shell window cleared by a java runtime program.
Maybe you are looking for
-
Start of cycle date is not taking while scheduling
Hi I have created a maintainance plan with scheduling indicator TIME and scheduling period 365 days . I am giving start of cycle date as 04-02-2011 but while scheduling the plan it is taking 19-02-2011 as first plan date . my maintainance plan cycle
-
IMac won't boot correctly! Braille-looking screen and purple lines
Hi guys; i've got a big problem over here; about a week ago my iMac (27", late 2009, i5 2,66ghz quad core, 4gb RAM upgraded to 12, running Snow Leopard) froze while watching a movie in streaming. After a few minutes i decided to force the turn off an
-
Hang after upgrading the Mac OS (10.6.7) last nite
Hi, I just updated the Mac OS last night. Before that, I uploaded lots of photos in iPhotos. After uploading and software update in the Mac and restarted, the iPhoto was hanged and did not respond. Any ideas to resolve it?? Pls kindly advise.
-
Ipod touch will not sync with itunes using windows 7 makes everything freeze
My itouch has not been able to sync with itunes using windows 7 for a couple of days. Everything just freezes and I have to reboot my laptop. I have reinstalled itunes and deleted the backup of the ipod but nothing is working.
-
Needing help ASAP!!!!!!!!!!!
I have had to uninstall and reinstall PS several times to get it to open so I can work, I am sick of doing this, It will not open when I right click on a photo or when I double click on the PS icon, how can I fix this? It was working fine till I did