• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Running UNIX command from Java

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 1067
2
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ya, I get the same problem.
 
Donny Wi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 .
 
After some pecan pie, you might want to cleanse your palatte with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic