• 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

Calling Runtime.getRuntime to execute a system command.

 
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I am trying to how to execute a system command in java.

Here is the code:

String cmd = "/usr/bin/pkill -9 -f " + "\'"+ getKillCmdLine() +"\'";
Runtime.getRuntime().exec(cmd);

My getKillCmdLine() returns


/home/yinglcs/bin/Main 9091 -DService10000000



(node there is space in the string.

But my code always fail with this:

- /usr/bin/pkill: invalid option -- 'D'
Usage: pkill [-SIGNAL] [-fvx] [-n|-o] [-P PPIDLIST] [-g PGRPLIST] [-s SIDLIST]
[-u EUIDLIST] [-U UIDLIST] [-G GIDLIST] [-t TERMLIST] [PATTERN]


I think the string does not get escaped "\'" and Runtime.getRuntime().exec() thinks '-D as an argument to the pkill command.

Can you please suggest any idea how to get this to work?

I try wrapping my string with ' and " and \"
String cmd = "/usr/bin/pkill -9 -f " + "'"+ getKillCmdLine() +"'";
String cmd = "/usr/bin/pkill -9 -f " + "\""+ getKillCmdLine() +"\"";

All does not work.

Thank you for any pointers.
 
Ranch Hand
Posts: 254
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does it work when you run the following commands in the console?

OR
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dealing with quotes and such is done by the shell when it parses the command; when you run with Runtime.exec(), there's no shell involved, so no parsing.

Instead of using the single-argument form of Runtime.exec(), use the other overloaded version that takes an array of Strings as an argument. Then the "kill command line" can be a single argument in that array -- i.e.,

String[] args = {"/usr/bin/pkill", "-9", "-f", getKillCmdLine() };
 
reply
    Bookmark Topic Watch Topic
  • New Topic