当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。