2012-03-27 65 views
1

Java中是否有可用於查詢作業的API?換句話說,我正在尋找api的「工作」命令,以便我可以瞭解作業的狀態(runningstopped等)。理想情況下,我希望能夠提交工作,但我認爲它可以通過調用shell和通過輕鬆實現&適用於Java的Linux shell作業API

+0

什麼樣的工作? – xxpor 2012-03-27 05:10:54

+0

就像你通過在Linux命令的末尾附加'&'提交的那些 – user837208 2012-03-27 05:12:55

+2

那些不是作業,它們是在後臺運行的進程。 – xxpor 2012-03-27 05:18:11

回答

1

如果你有/ develop - shell腳本來處理Job,那麼你可以使用java.lang.process apis來執行那個shell腳本看看它是否能滿足你的目的。您也可以將參數和參數一起傳遞。以下是代碼片段可能對您有用。

import java.io.IOException; 
import java.io.InputStream; 


public class MYProcess 
{ 
    int startProcess() 
    { 
     String cmd = "/opt/test/bin/mystart.sh" 

     // create a process for the shell 
     ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); 
    // use this to capture messages sent to stderr 
     pb.redirectErrorStream(true);          
     Process shell = null; 
     int shellExitStatus =-1;  
     try 
     { 
     shell = pb.start(); 
     } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 
     InputStream shellIn = shell.getInputStream(); 
     try 
     { 
     shellExitStatus = shell.waitFor(); 
     //logger.info("call exit status:" + shellExitStatus); 
     //logger.info("If exit status is not zero then call is not successful. Check log file.");   
     } 
     catch (InterruptedException e) 
     { 
     //logger.error("error while call" + e); 
     e.printStackTrace(); 
     } // wait for the shell to finish and get the return code 
     return shellExitStatus; 
    } 
} 
1

我認爲你在找什麼是java.lang.process,但它實際上不能返回狀態(運行,停止等),而是隻能返回輸出(err,std)或退出值。

+0

這似乎只適用於當前正在運行的進程。從他/她的問題來看,他們似乎想知道一個任意PID的過程。 – xxpor 2012-03-27 05:18:53

+0

據我所知,沒有內置API來查詢PID進程。但是因爲你可以像'ps'一樣調用shell任務並獲得輸出,所以它不應該很難用Java存檔。 – 2012-03-27 05:33:15

+0

我的擔憂只是因爲Java試圖跨平臺,他們會故意難以實現,因爲流程管理非常依賴底層平臺。 – xxpor 2012-03-27 05:35:46

1

可以通過ProcessBuilder /運行時apis調用Shell命令。除此之外,沒有Java API。 (I doubt即使是C api也存在,如果是這樣,你可以使用JNI和控制進程)