wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Running UNIX command from Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Running UNIX command from Java" Watch "Running UNIX command from Java" New topic
Author

Running UNIX command from Java

Donny Wi
Greenhorn

Joined: Jan 24, 2002
Posts: 13
I'm having problem running the UNIX "grep" command from java.
This is what my code looks like:

When I ran the "grep" command above, it return exit code=1, which means no match found.
When I replace the "grep" command with "ls", it works fine. When I replace the "grep" command with "wc -l", first it returns zero but when I added a empty loop to delay the parent program, I got the right value.
I use waitFor() method, but I think it does not work well.
Can someone please help me or tell my why "grep" command does not work from Java?


Donny Widjaja
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 984

Ya, I get the same problem.
Donny Wi
Greenhorn

Joined: Jan 24, 2002
Posts: 13
I found the answer but I can't explain why:
Instead of using
1. Runtime.getRuntime().exec(sCommand);
I use
2. Runtime.getRuntime().exec(new String[] {"/usr/bin/sh", "-c", sCommand});
I saw some example that runs multiple command by using code number 2, so I just experiment with the code and suddently the process.waitFor() will actually wait until the sub-process is complete. I don't know why.
So, there was my 10 hours of experiment with Runtime class in Java.
Donny
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Just think how many OTHER people will not have to waste 10 hours discovering that - just because of YOU.
You should be pleased with yourself . WE are .
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Running UNIX command from Java
 
Similar Threads
How to connect to Linux using Java code?
How to invoke 'exe' in JSP
Pesky Runtime method
java program run external command on Unix
problem running sqlplus using Runtime.exec()