Runtime.exec() with envp[] array
I ran into an unsual problem.
If I set an env array variable to something (at least one pair), then certain applications fail to start through Runtime.exec(command[], env[]). For example, my own java classes that require various xml and ftp libraries. The particular exception has been mentioned on the forum ( ie. Unrecognized Windows Sockets error: 10106:).
It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
thanks,
eugene
>
It has to do with environment variables not being set for new process. When I do NOT set env[] variable (or pass null) then current env is used in .exec() call and everything works fine.
So my question is how do I set my environment variables and/or append them to existing set.Or said differently if I pass a non-null array, current env set is not copied over.
>
If you're using 1.5, you can create a java.lang.ProcessBuilder object rather than calling Runtime.exec(). The ProcessBuilder inherits the environment of the calling process, but then allows you to update individual entries.
In 1.4, I don't believe that you can get a complete copy of the invoker's environment.
Similar Messages
-
Runtime.exec() with .bat-files in a jar
Hi All,
I've written a java-Program, which calls .bat-files per Runtime.exec() for some OS-specific tasks.
Everything works fine, but if I want to pack the whole code and the .bat-files into several jars, I can't get the bat-files to run. I have tried to get it to work with "getClass().getResource()" as I do the same for my Images, and the returned URL seems to be OK so far (something like jar:file:/c:/test.jar! testpkg/test.bat). I converted this URL into a String and tried to run Runtime.exec() with it, but I always get a Runtime-Exception.
The String looks exactly like the URL, when I print them to console.
These bat-files are essential for the application and I would not try to pack them into a jar if I hadn't to distribute this application as a signed applet to unknown users, too.
I hope there is anyone out there who can tell me if and how it is possible to run an external program out of java, which is packed into a jar, so thanx in advance to any helpful replies.
acdekaYou can't run the .bats simply because the shell can't access it. You tell it to run a file that simply doesn't exist in the OS.
-
Runtime.exec() with language specific chars (umlauts)
Hello,
my problem is as follows:
I need to run the glimpse search engine from a java application on solaris using JRE 1.3.1 with a search pattern containing special characters.
Glimpse has indexed UTF8 coded XML files that can contain text with language specific characters in different languages (i.e. german umlauts, spanish, chinese). The following code works fine on windows and with JRE 1.2.2 on solaris too:
String sSearchedFreeText = "Tür";
String sEncoding = "UTF8";
// Convert UTF8 search free text
ByteArrayOutputStream osByteArray = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(osByteArray, sEncoding);
w.write(sSearchedFreeText);
w.close();
// Generate process
String commandString = "glimpse -y -l -i -H /data/glimpseindex -W -L 20 {" + osByteArray.toString() + "}";
Process p = Runtime.getRuntime().exec(commandString);
One of the XML files contains:
<group topic="service-num">
<entry name="id">7059</entry>
<entry name="name">Türverkleidung</entry>
</group>
Running the java code with JRE 1.2.2 on solaris i get following correct commandline
glimpse -y -l -i -H /data/glimpseindex -W -L 20 {Türverkleidung}
--> glimpse finds correct filenames
Running it with JRE 1.3.1 i get following incorrect commandline
glimpse -y -l -i -H /data/glimpseindex -W -L 20 {T??rverkleidung}
--> glimpse finds nothing
JRE 1.2.2 uses as default charset ISO-8859-1 but JRE 1.3.1 uses ASCII on solaris.
Is it possible to change the default charset for the JVM in solaris environment?
Or is there a way to force encoding used by Runtime.exec() with java code?
Thanks in advance for any hints.
KarstenosByteArray.toString()Yes, there's a way to force the encoding. You provide it as a parameter to the toString() method.
-
Runtime.exec() with japanese arguments?
I'm trying to invoke a C++ executable from java using the Runtime.exec() method. The C++ application accepts a filename as a command line argument & opens the file. This C++ app is unicode enabled i.e. it can accept UTF-16 (wide char) parameters. Howevere, when i invoke this application using Java's Runtime.exec() and specify a japanese file name as an argument, the japanese characters get converted to '?' characters by the time they are received in the C++ application. I'm running this application on Windows 2K, default i.e. English version.
Looking at the source code of Runtime class, it seems that the exec()
function makes use of a native helper function - execInternal(). Does
this function support the entire unicode range?
Is there any way we can avoid the conversion of japanese characters to '?' characters? Also, is there any other alternative for invoking an external application with Unicode (Say, japanese) arguments?
Please reply ASAP.
Thanks!I have a very similar problem. I am invoking cvs through Runtime.exec, and I am using it to add and check in files with chinese characters in the name, and it is failing with the following cvs error:
Could not add resource file 纳出 in directory C:\test to repository: cvs add: nothing known about ??
The error message comes from cvs, and I have been able to track it down to the call string I pass to exec. It is correct when passed in but the command fails. For laughs I tried to call something simpler, like mkdir:
err mkdir ?? is: The filename, directory name, or volume label syntax is incorrect.
It seems pretty clear to me that although the callstring is correct, the call to exec fails, and the special characters are replaced with questionmarks, which seems to me to be an encoding issue.
Did you get any solution to your problem, or does anyoen else have an answer for this? -
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() with get command output
hi,
How can i get output of command which i run with runtime.exec().
p.e.:
Process p;
Runtime r = Runtime.getRuntime();
p = r.exec("net use \\pc\dir pswd /user:username");
if command was done succesfully that in cmd is return this:
"The command completed successfully." I can get this text, but i dont know how.
Plese help
thank you
PaloLook at the API for Process
-
Runtime.exec with a unix shell script
I've done a lot of google'ing and haven't found a definitive answer to my question, including the JavaWorld article that is pointed to quite often. Scenario1 - The program calling Runtime.exec is running in /dir1 and I have a script called test.sh in /dir2 (neither directory are in the path). If I call Runtime.exec("test.sh", null, "/dir2"), I get java.io.IOException: test.sh: not found. However, if I do "touch test.sh" AND "chmod +x test.sh" in /dir1 and call the same exec, it works AND runs the script in /dir2 not /dir1?!?! Also, if I copy /dir2/test.sh /dir1/test.sh and I call exec("test.sh"), it works fine. Scenario2 - If I get rid of /dir1/test.sh and call exec("/dir2/test.sh", null, "/dir2") OR exec("/bin/sh test.sh", null, "/dir2") - both of those work. I just don't get Scenario1. Why does having the dummy executable test.sh in /dir1 allow it to run in /dir2 OR if the script is in the local directory of the process calling exec, why does it work without adding the path? It doesn't seem consistent. Seems like the working directory I specify isn't set before trying to run it or something. On the flip side, if I have a java class in /dir2 called test.class, I can call exec("java test", null, "/dir2") and it just runs without jumping through any hoops - although I think the explanation for that is that "java" is in the path. Let me know what you think.
GaryI think the problem is that the three argument version of exec specifies the command to run (should be full path to it if it is not in the current dir), the environment, then the working directory. The working directory will not help java to find the command to run in the first place. The following does work as you say:
Runtime.exec("/bin/sh test.sh",null,"/dir2");This is because the full path to the command (/bin/sh) is specified, that runs in directory /dir2 then tries to find test.sh which it finds there.
Basically to run anything, you should specify the full path in the command, the working directory will not help java find it.
Dave -
Runtime.exec with Unix script
I want to execute unix script xxx.sh that I write it for running something and I will execute that script via java class I use
Runtime runTime = Runtime.getRuntime();
Process procRun = runTime.exec("/xxx/yyyy/testing.sh");
xxx and yyyy is path in my unix server and testing.sh is unix script
when I run this class it return true result but that unix script doesn't working or execute following my program in java class
please help me to solve this problem
Regards,
sobigwhen I run this class it return true result but that unix script doesn't
working or execute following my program in java classwhat do you mean it returns true....
and how do you know that it does not execute your script.... its probably going to be started as a bg process.... try doing something like creating a directory or something in the script .sh to be sure that it ran.... (just for testing).... im quite sure that it will execute a .sh file like that.... -
Stuck On Runtime.exec() with cmd.exe
I've done my best to look through the forums and implement what's been said but I'm getting a problem where my whole Java program freezes when the exec() is executed. Can anyone tell me what I'm missing or have misunderstood ?
try
Process runSmodels = Runtime.getRuntime().exec("C:\\Windows\\System32\\cmd.exe lparse predict.pl | smodels 0");
String smodelsOutput = new String();
BufferedReader smodelsReader = new BufferedReader(new InputStreamReader(runSmodels.getInputStream()));
String outputLine = smodelsReader.readLine();
while(outputLine != null)
smodelsOutput += outputLine;
outputLine = smodelsReader.readLine();
smodelsReader.close();
System.out.println(smodelsOutput);
catch(IOException exc)
JOptionPane.showMessageDialog(rootPane, "Could not access Smodels.", "System Call Error", JOptionPane.ERROR_MESSAGE);
}DarioAtUOW wrote:
Pitfall 1 : Calling .exitValue(). My code doesn't do that.
Pitfall 2 :Not enptying relevant streams. I do empty the input stream.
Pitfall 3 : Assuming a command is an executable program. I don't do that, cmd.exe is in my command string explicitly.
Pitfall 4 : As above in Pitfall 3.
So, why accuse me of not reading the article ? You probably have many years of experience at Java, unlike me, who is just starting out with it at university.Pitfall 2 : Even though you are processing stdout you are not processing stderr! Always always always process both. This may or may not be the cause of your problem but by copying the process stderr to your System.err you may see why your process is stuck.
Even Clippy, the Microsoft Office Assistant, could answer questions better than you have attempted to do.Ouch, I'm cut to the bone on your razor sharp wit. Phuck you. -
Hi,
well i want to execute wget command in a java class and print sdout in the shell
this is my code:
try {
Process ls_proc = Runtime.getRuntime().exec("wget http://antimilkado.free.fr/ted/screenshot.png");
BufferedReader ls_in = new BufferedReader(new InputStreamReader(ls_proc.getInputStream()));
try {
while ((ls_str = ls_in.readLine()) != null) {
System.out.println(ls_str);
catch (IOException e) {
System.err.println(e);
System.exit(0);
}I've tested with other basic command like ls and co., it works but not with a wget, nothing is printed...
I guess my code is good and there is maybe a problem with wget command i don't know
If someone gets it :)
thx
++
SHiSo1) Get the InputStream from the connection.
2) Open a FileOutpupStream to the file you wish to write.
3) Loop reading bytes from the InputStream and write them to the FileOutputStream until you get EOF.
e.g.
InputStream is = ...
FileOutputStream os = ...
byte[] buffer = new byte[4096];// or any size you want
for (int count = 0; (count = is.read(buffer)) >= 0;)
os.write(buffer, 0, count);
4) flush() then close() the FileOuputStream. -
I there!
i've a problem calling linux commands with blanks.
eg:
---snip---
String cpCommand = "cp /home/bullseye/my file.txt /tmp/tempFile.tmp";
Process p = Runtime.getRuntime().exec(cpCommand);
return p.waitFor()
---snip---
i've tried with
String cpCommand = "cp /home/bullseye/my\ file.txt /tmp/tempFile.tmp";
and
String cpCommand = "cp \"/home/bullseye/my file.txt\" \"/tmp/tempFile.tmp\"";
but nothing works....
could someone help me?!
thx-a-lotI tried this command in Unix and it works.
cp "/home/bullseye/my file.txt" /tmp/tempFile.tmp
The java String for this will be
String cpCommand = "cp \"/home/bullseye/my file.txt\" /tmp/tempFile.tmp";Hope this helps.
vinod. -
Runtime.Exec with cmd and problem in waitFor
Hi
I am running
Process p1 = Runtime.getRuntime().exec("cmd /c start /min <some.exe> <args to exe>");
then I am checking
Int ExitVal = p1.waitFor;
If (ExitVal != 0) and so on.
However, the problem is that the p1.waitFor does not really block the thread. It returns 0 and the program continues even though the some.exe has still not completed its execution.
My guess is that Java is giving the exitcode of cmd.exe and not some.exe.
If this analysis is correct, I am stumped. How do I get the exit code of some.exe?
If my analysis is wrong, please help me in the right direction.
Regards
Shreekar"Enables a user to start a separate window in Windows
from the MS-DOS prompt."<p>
Again, I read it afterwards. However, another funny thing is happening now. Initially my command was
"cmd start /min (some.exe) (some args) > somefile.txt"
(I know I missed to show the output redirection in my original post.)
</p>
<p>
Then I removed "start /min", it is working as expected.
Then I removed the output redirection and now it hangs !!!
I put back the output redirection and it is working. Does the output redirection make it wait in some way and force it to exit gracefully?
</p>
Any ideas? -
Runtime.exec() with ping
Hi all,
I have looked at the previous threads about this and am aware there are no API's for ping. I need a simple app that just pings three servers to verify they are still up. The problem i am having is that it seems that my process just hangs. below is the code. any help would be much appriciated.
thanks in advance.
try{
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cmd ping xxx.xxx.xxx.xxx);
InputStream stderr = p.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
System.out.println("Process exitVal " + exitVal);
}//end try
catch (Throwable t){
t.getMessage();
}1) its .exec("ping 192.168.0.1") , no "cmd ping"
2) missing a quote at the end of your rt.exec call.
Process p = rt.exec("ping " + enterHostHere); -
Runtime.exec() with su -c comand in Linux
I try to run the command su -c "any command" but two thinks work wrong; First I have the message "standard in must be a tty" and the other, if I solution this how can I pass my root password for command su??
for example, this is my sample code.
import java.io.*;
public class Teste
public static void main (String[] args)
try
String cmd[] = {"su","-c","\"ls /home/andre\""};
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader br = new BufferedReader ( new InputStreamReader ( p.getInputStream() ));
String s1;
while ( ( s1 = br.readLine() ) != null ) System.out.println(s1);
br = new BufferedReader (new InputStreamReader (p.getErrorStream() ));
while ( ( s1 = br.readLine() ) != null ) System.out.println(s1);
catch (IOException ioe)
System.out.println(ioe);
}su has detected that its standard input not from a terminal.
It is not a good way to try to mimic an interactive "su" session In order to obtain privileged (root) access programatically.
Confer the "sudo" command or the setuid permission bits. -
Problems with Runtime.exec() and certain Unix processes
Certain Unix processes don't behave correctly when run from Java using Runtime.exec(). This can be seen by running /bin/sh and trying to interact with it interactively. The issue appears to be that /bin/sh (and many other Unix tools) are checking the file handles on the spawned process to see if they are associated with a TTY.
Is there any way to associate a process spawned by Runtime.exec() with a terminal or alternatively, is there a JNI library available that would setup the process correctly and still provide access to the input and output streams?
Our objective is to have the flexibility of expect in being able to run and interact with spawned processes. A bug was opened at one point but closed back in 1997 as being a fault in the spawned process, not Java.
Bug ID: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4058689#include <stdio.h>
void doit() {
int c;
while((c=getc(stdin)) != EOF) {
printf("%c",c);
int main() {
freopen("/dev/tty", "r", stdin);
doit();
}This program reopens its standard input against /dev/tty and catenates it to stdout. And voila, it takes its standard input from the terminal, even though it was started with stdin against /dev/null..
$ gcc b.c -o b
$./b < /dev/null
buon giorno
buon giorno
Maybe you are looking for
-
Dual CPU fans in IQ816 Question
I have received the fatal error message indicating that my wife's IQ816 CPU fan is dead. When I opened up the unit I found that one of the 2 CPU fans was indeed not functioning (FYI there are a total of 3 fans in the IQ816s). The fans part number (o
-
Using sql expressions in interfaces
Hi All, I have created an interface that works very fine when used with constants. But when i am using a sql case expression for populating a target column, the target column value is updated as null. The expression that i have written is: CASE WHEN
-
I cant export my movie, as there is no share tab and when i go file>share it isn't in the right format what should i do?
-
Correcting the date stamp with files converted with mpgstreamclip.
I have converted some files using streamclip but it changes the date of the file to the date of the conversion. When I try importing them into imovie they are sorted incorrectly. The files were recorded in 07 but now have the date stamp of today. Can
-
after a paper jam was cleared, (already went thru the online trouble shooting procedures) this is the message on the printer display: "Carriage Jam" "The print carriage cannot move." The printer is still under warranty and I need to know how t