Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Runtime exec throws no such file or permission denied

My program is running on ubuntu 10.04 ,and here is the code :

Process process=Runtime.getRuntime().exec("ls",null,null);

it throw an exception of :

Cannot run program "ls": java.io.IOException: error=2, No such file or directory,  

and i tried to change "ls " to "chmod" ,"pwd" ,i found no one shell command work, all came to the same problem .(I also tried "/bin/sh -c ls")

and then i change the code to :

Process process=Runtime.getRuntime().exec("/bin/ls",null,null);

it throw an exception of :

Cannot run program "/bin/ls": java.io.IOException: error=13, Permission denied

I have changed privilege of all the related files and directories to 777 so i really don't know what's wrong with it.

Thank you for your replies .

like image 393
libing Avatar asked Jun 14 '12 11:06

libing


1 Answers

Process process=Runtime.getRuntime().exec("ls",null,null);

This is expected give a No such file or directory exception since ls is most likely not in the current working directory of your program. When you type ls from the Linux shell prompt, it uses the PATH environment variable to turn ls into /bin/ls. Runtime does not do this for you.

You need to specify the full path "/bin/ls". You should be using the Runtime.exec("/bin/ls") method and not passing in the null arguments.

Process process=Runtime.getRuntime().exec("/bin/ls");

Your comments seem to indicate that even when you use this call, you are getting a Permission denied exception. This works for me from a standard Java executable. I assume that you can do a /bin/ls from the Linux command line successfully? /bin/ls (and the associated directories) should be 755 and not 777 which would be a security nightmare. But 777 should work.

Maybe you are running some sort of protected JDK? Applets, for example, do not have permissions to execute Unix commands for security reasons. Maybe you have a restrictive Java policy file and you need to add execute permissions?

like image 92
Gray Avatar answered Oct 19 '22 19:10

Gray