Java語言以其跨平臺性和簡易性而著稱,在Java裏面的lang包裏(java.lang.Runtime)提供了一個允許Java程序與該程序所運行的環境交互的接口,這就是Runtime類,在Runtime類裏提供了獲取當前運行環境的接口。 其中的exec函數返回一個執行shell命令的子進程。exec函數的具體實現形式有以下幾種:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws IOException
public Process exec(String command,String[] envp,File dir) throws IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws IOException
public Process exec(String[] cmdarray, String[] envp,File dir) throws IOException
代碼如下:
try
{
String commands = "ls -l";
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());
}
上面的代碼首先是聲明瞭一個代表命令的字符串commands,它代表了ls -l 這個命令。之後我們用Runtime.getRuntime().exec(commands)來生成一個子進程來執行這個命令,如果這句話運行成功,則 命令 ls -l 運行成功(由於沒有讓它顯示,不會顯示ls -l 的結果)。後面的流操作則是獲取進程的流信息,並把它們一行行輸出到屏幕。
2)執行帶有參數的命令(尤其是參數需要用引號的)時則需要用String的數組來表示整個命令,而且要用轉義符把引號的特殊含義去除,例如我們要執行 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());
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());
1)system(shell命令或shell腳本路徑);
system()會調用fork()產生子進程,由子進程來調用/bin/sh-c string來執行參數string字符串所代表的命令,此命令執行完後隨即返回原調用的進程。在調用system()期間SIGCHLD 信號會被暫時擱置,SIGINT和SIGQUIT 信號則會被忽略。
返回值:如果system()在調用/bin/sh時失敗則返回127,其他失敗原因返回-1。若參數string爲空指針(NULL),則返回非零值。如果 system()調用成功則最後會返回執行shell命令後的返回值,但是此返回值也有可能爲system()調用/bin/sh失敗所返回的127,因此最好能再檢查errno 來確認執行成功。
例:在~/test/目錄下有shell腳本test.sh,內容爲
#test.sh
echo hello
{
system("~/test/test.sh");
}
[root@localhost test]$./system_test
hello
[root@localhost test]$
2)popen(char *command,char *type)
main
{
FILE * fp;
charbuffer[80];
fp=popen(“~/myprogram/test.sh”,”r”);
fgets(buffer,sizeof(buffer),fp);
printf(“%s”,buffer);
pclose(fp);
}
[root@localhost test]$ gcc popentest.c -o popentest
[root@localhost test]$ ./popentest
/root/test
[root@localhost test]$