java執行shell命令,判斷命令是否執行完,並解決wait for()鎖死問題

java執行shell命令

    使用到Process和Runtime兩個類,返回值經過Process類的getInputStream()方法獲取java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ReadCmdLine {
	public static void main(String args[]) {
		Process process = null;
		List<String> processList = new ArrayList<String>();
		try {
			process = Runtime.getRuntime().exec("df -hl");
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = "";
			while ((line = input.readLine()) != null) {
				processList.add(line);
			}
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		for (String line : processList) {
			System.out.println(line);
		}
	}
}

 

java執行命令時,判斷命令是否執行結束

    一般咱們在第一步執行完調用後,須要知道命令是否執行完畢,則須要經過wait for()來實現git

Process proc = Runtime.getRuntime().exec("xx.exe");

            try {
                if (proc.waitFor() != 0) {
                    System.err.println("exit value = " +
                        proc.exitValue());
                }
            }
            catch (InterruptedException e) {
                System.err.println(e);
            }

proc.waitfor()的返回結果若是不爲0,則執行異常,爲0,則命令執行正確。github

 

解決waitfor()阻塞或者鎖死的問題

        緣由:因爲 JVM 提供標準輸入和輸出流的緩衝區大小是十分有限,很快的讀入或者輸出流將會致使進程阻塞或者鎖死。shell

        解決方法:再調用兩個線程分別輸出標準輸出流和標準錯誤流,這樣就能夠解決標準輸出和錯誤流緩衝區限制而致使的阻塞和鎖死狀態了。函數

        解決線程阻塞和鎖死的類以下:this

class RunThread extends Thread
{
    InputStream is;
    String type;
    
    RunThread(InputStream is, String printType)
    {
        this.is = is;
        this.printType = printType;
    }
    
    public void run()
    {
        try
        {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(PrintType + ">" + line);
            } catch (IOException ioe)
              {
                ioe.printStackTrace();
              }
    }
}

        執行外部命令的主函數:spa

public class Runpro {
    public void main(String arg[]){ 
        try {
            System.out.println("cmd start");
            Process p = Runtime.getRuntime().exec("pwd");  //調用Linux的相關命令  
            new RunThread(p.getInputStream(), "INFO").start(); 
            new RunThread(p.getErrorStream(),"ERR").start();
            int value = p.waitFor();
            if(value == 0)
        	System.out.println("complete");
            else
        	System.out.println("failuer");
        } catch (IOException e) {
            e.printStackTrace();
        }
       }
    }

詳細介紹請見 http://yangfangs.github.io/2016/03/16/java-waitfor-block-deadlock/#waitfor%E9%98%BB%E5%A1%9E%E6%88%96%E9%94%81%E6%AD%BB%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95線程

相關文章
相關標籤/搜索