JAVA 調用C 語言程序,並且進行傳參收結果等操作

對於以下命令:

 

ls /var/log/nginx/access.log.*

 

ls /var/log/nginx/access.log.* | grep 2011-05-16

 

grep "test=123&name=opencfg.com" /var/log/nginx/access.log.* > /root/alert.log

 

類似這樣的命令,process.exec是不會理解其中的*號與> 甚至管道符號|

 

這是由於在linux環境下,我們一般使用bash shell調用這些命令, 而其中的一些符號 諸如:

 

*, ?, >, < , | 這樣的符號是通過/bin/bash -c來做解釋後再傳遞給 所調用的命令

 

/bin/bash -c 這個參數已經作爲默認命令,在系統啓動時加載到運行環境中,所以我們敲以上命令的時候可以省略

 

但對於java的Process來說,不會識別這些符號,因此我們必須強制調用/bin/bash -c來幫我們做符號解釋:

 

 

下邊是一段測試代碼:

 

Java代碼  收藏代碼
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3.   
  4. /** 
  5.  * CommandTest 
  6.  *  
  7.  * @author opencfg.com 
  8.  * @since 0.0.1-SNAPSHOT 
  9.  * @version 0.0.1-SNAPSHOT 
  10.  * @date 2011-05-17 
  11.  */  
  12. public class CommandTest {  
  13.   
  14.     public static void main(String[] args) throws Exception {  
  15.         // 1.test console args commands  
  16.         // exec("args", args);  
  17.   
  18.         String[] commands = new String[] { "/bin/bash""-c""grep -h 200.*370.*http /var/log/nginx/access.log.* > /root/test_123.log" };  
  19.         String[] commands_ls = new String[] { "/bin/bash""-c""ls /var/log/nginx/access.log.*" };  
  20.   
  21.         // 1.test java string commands  
  22.         exec("commands", commands);  
  23.     }  
  24.   
  25.     public static void exec(String message, String[] args) throws Exception {  
  26.         print(message + ":");  
  27.         Process process = Runtime.getRuntime().exec(args);  
  28.         for (String arg : args) {  
  29.             System.out.println(arg);  
  30.             System.out.print(" ");  
  31.         }  
  32.         BufferedReader errorReader = new BufferedReader(new InputStreamReader(  
  33.                 process.getInputStream()));  
  34.         String line = null;  
  35.         while ((line = errorReader.readLine()) != null) {  
  36.             System.err.println(line);  
  37.         }  
  38.         errorReader.close();  
  39.         BufferedReader infoReader = new BufferedReader(new InputStreamReader(  
  40.                 process.getErrorStream()));  
  41.         while ((line = infoReader.readLine()) != null) {  
  42.             System.out.println(line);  
  43.         }  
  44.         infoReader.close();  
  45.         print("");  
  46.     }  
  47.   
  48.     public static void print(String[] args) {  
  49.         for (String arg : args) {  
  50.             System.out.println(arg);  
  51.             System.out.print(" ");  
  52.         }  
  53.     }  
  54.   
  55.     public static void print(String arg) {  
  56.         System.out.println(arg);  
  57.     }  
  58.   
  59. }  

特別需要注意的是,當需要執行的linux命令帶有管道符時(例如:ps -ef|grep java),用上面的方法是不行的,解決方式是將需要執行的命令作爲參數傳給shell

[java] view plaincopy
  1. public class Test {  
  2.     public static void main(String[] args) throws Exception{  
  3.         String[] cmds = {"/bin/sh","-c","ps -ef|grep java"};  
  4.         Process pro = Runtime.getRuntime().exec(cmds);  
  5.         pro.waitFor();  
  6.         InputStream in = pro.getInputStream();  
  7.         BufferedReader read = new BufferedReader(new InputStreamReader(in));  
  8.         String line = null;  
  9.         while((line = read.readLine())!=null){  
  10.             System.out.println(line);  
  11.         }  
  12.     }  
  13. }  
find / -name "*mysql*" -print 時,用如下代碼
       
try            
String[] commands = new
String[]{"find",".","-name","*mysql*","-print"};
           
Process process = Runtime.getRuntime().exec (commands);
           
InputStreamReader ir=new
InputStreamReader(process.getInputStream());
           
BufferedReader input = new BufferedReader (ir);
           
String line;
           
while ((line = input.readLine ()) != null){
               
System.out.println(line);
        
}//end try
       
catch (java.io.IOException e){
           
System.err.println ("IOException " + e.getMessage());
3)執行一個自己寫的腳本
非常簡單,只需要在構造commands時寫出它的詳細路徑和文件名,及參數等。
   try
           
String commands = "/root/test/checkfile.sh";
           
Process process = Runtime.getRuntime().exec (commands);
           
InputStreamReader ir=new
InputStreamReader(process.getInputStream());
           
BufferedReader input = new BufferedReader (ir);
           
String line;
           
while ((line = input.readLine ()) != null){
               
System.out.println(line);
        
}//end try
       
catch (java.io.IOException e){
           
System.err.println ("IOException " + e.getMessage());
 
如果命令中有參數,同2)要用數組的形式。


import java.io.*;

import java.lang.*;
class test3{
       public static void main(String []args) throws IOException{
                long a = System.currentTimeMillis();
                Process process = Runtime.getRuntime().exec("/home/zhangdi/traceroute_l");//這是外部程序所在目錄,切記返回類型爲process
                PrintStream outputWriter = new PrintStream(new BufferedOutputStream(process.getOutputStream()));
                outputWriter.println("218.198.33.204");
                outputWriter.flush();//這裏一定要刷新緩衝區,不然參數傳不過去
                outputWriter.println("-T");
                outputWriter.flush();
                outputWriter.println("-80");
                outputWriter.flush();
                outputWriter.println("4");
                outputWriter.flush();
                outputWriter.println("192.168.1.30");
                outputWriter.flush();
                BufferedReader addResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while((line=addResult.readLine())!=null)
                {
                     
                        System.out.println(line);
                 }
                long b = System.currentTimeMillis();
                System.out.println(b-a);
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章