當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.lang.Process用法及代碼示例


抽象 Process 類是一個進程,即一個正在執行的程序。 Process提供的方法用於執行輸入、輸出、等待進程完成、檢查進程的退出狀態以及銷毀進程。

  • 它擴展了類對象.
  • 它主要用作運行時類中 exec() 創建的對象類型的超類。
  • ProcessBuilder.start()Runtime.getRuntime.exec()方法創建一個本機進程並返回一個子類的實例過程可用於控製過程並獲取有關過程的信息。
  • ProcessBuilder.start() 是創建進程的首選方法。

ProcessBuilder.start() 與 Runtime.getRuntime.exec():ProcessBuilder 允許我們將子進程的標準錯誤重定向到其標準輸出。現在我們不需要兩個單獨的線程,一個從 stdout 讀取,一個從 stderr 讀取。構造函數

  • Process():這是唯一的構造函數。

方法:

  1. 無效destroyForcibly():殺死子進程。
Syntax: public abstract void destroyForcibly().
Returns: NA.
Exception: NA.

Java


// Java code illustrating destroyForcibly()
// method for windows operating system
// Class
public class ProcessDemo {
    // Main driver method
    public static void main(String[] args)
    {
        try {
            // create a new process
            System.out.println("Creating Process");
            ProcessBuilder builder = new ProcessBuilder("notepad.exe");
            Process pro = builder.start();
            // wait 10 seconds
            System.out.println("Waiting");
            Thread.sleep(10000);
            // kill the process
            pro.destroyForcibly();
            System.out.println("Process destroyed");
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

輸出:

Creating Process
Waiting
Process destroyed

Java


// Java code illustrating destroyForcibly()
// method for Mac Operating System
import java.io.*;
import java.lang.*;
class ProcessDemo {
    public static void main(String arg[])
        throws IOException, Exception
    {
        System.out.println("Creating process");
        // creating process
        ProcessBuilder p = new ProcessBuilder(new String[] {
            "open", "/ Applications / Facetime.app"
        });
        Process pro = p.start();
        // waiting for 10 second
        Thread.sleep(10000);
        System.out.println("destroying process");
        // destroying process
        pro.destroyForcibly();
    }
}

輸出:

Creating process
destroying process

int exitValue():此方法返回子進程的退出值。

Syntax: public abstract int exitValue().
Returns: This method returns the exit value of 
the subprocess represented by this Process object. 
By convention, the value 0 indicates normal termination.
Exception: IllegalThreadStateException ,
if the subprocess represented by this Process object has not yet terminated.

Java


// Java code illustrating exitValue() method
public class ProcessDemo {
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
            // create a new process
            System.out.println("Creating Process");
            ProcessBuilder builder = new ProcessBuilder("notepad.exe");
            Process pro = builder.start();
            // kill the process
            pro.destroy();
            // checking the exit value of subprocess
            System.out.println("exit value:" + pro.exitValue());
        }
        // Catch block to handle the exceptions
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

輸出:

Creating Process
1

Abstract InputStream getErrorStream():該方法獲取子進程的輸入流。

Syntax: public abstract InputStream getInputStream().
Returns: input stream that reads input from the process out output stream.
Exception: NA.

Java


// Java code illustrating
// getInputStream() method
import java.io.*;
import java.lang.*;
class ProcessDemo {
    public static void main(String arg[])
        throws IOException, Exception
    {
        // creating the process
        Runtime r = Runtime.getRuntime();
        // shell script for loop from 1 to 3
        String[] nargs = { "sh", "-c", "for i in 1 2 3; do echo $i; done"};
    Process p = r.exec(nargs);
    BufferedReader is = new BufferedReader(
        new InputStreamReader(p.getInputStream()));
    String line;
    // reading the output
    while ((line = is.readLine()) != null)
        System.out.println(line);
}
}

輸出:

1
2
3

Abstract OutputStream getOutputStream():該方法獲取子進程的輸出流。流的輸出通過管道傳輸到此 Process 對象表示的進程的標準輸入流中。

Syntax: public abstract OutputStream getOutputStream()
Returns: the output stream connected to the normal input of the subprocess.
Exception: NA.

Java


// Java code illustrating 
// getOutputStream() method
import java.io.BufferedOutputStream;
import java.io.OutputStream;
public class ProcessDemo 
{
    public static void main(String[] args)
    {
        try
        {
            // create a new process
            System.out.println("Creating Process");
            Process p = Runtime.getRuntime().exec("notepad.exe");
     
            // get the output stream
            OutputStream out = p.getOutputStream();
     
            // close the output stream
            System.out.println("Closing the output stream");
            out.close();
        } 
            catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }
}

輸出:

Creating Process...
Closing the output stream...

Abstract InputStream getErrorStream():它返回一個輸入流,該輸入流從進程錯誤輸出流讀取輸入。

Syntax: public abstract InputStream getErrorStream().
Returns: the input stream connected to the error stream of the subprocess.
Exception: NA.

Java


// Java code illustrating 
// getErrorStream() method
import java.io.InputStream;
public class ProcessDemo
{
    public static void main(String[] args) 
    {
        try
        {
              // create a new process
            System.out.println("Creating Process");
             
            Process p = Runtime.getRuntime().exec("notepad.exe";);
     
            // get the error stream of the process and print it
            InputStream error = p.getErrorStream();
             
            for (int i = 0; i < error.available(); i++) 
            {
                System.out.println(" " + error.read());
            }
     
            // wait for 10 seconds and then destroy the process
            Thread.sleep(10000);
            p.destroy();
     
        } 
         
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }
}

輸出:

Creating Process

int waitFor():返回進程返回的退出代碼。在調用該方法的進程終止之前,該方法不會返回。

Syntax: public int waitFor().
Returns: the exit value of the process. By convention, 0 indicates normal termination.
Exception: throws InterruptedException.

Java


// Java code illustrating 
// waitFor() method
public class ProcessDemo 
{
    public static void main(String[] args) 
    {
        try
        {
            // create a new process
            System.out.println("Creating Process");
            Process p = Runtime.getRuntime().exec("notepad.exe");
     
            // cause this process to stop
                // until process p is terminated
            p.waitFor();
     
            // when you manually close notepad.exe
                // program will continue here
            System.out.println("Waiting over");
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }
}
  1. 輸出:
Creating Process...
Waiting over.



相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 Java.lang.Process class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。