From e265b07fc9e7b5499c6d98ed0f4cd17e12e3967a Mon Sep 17 00:00:00 2001 From: lee Date: Fri, 29 Apr 2022 09:53:55 +0100 Subject: [PATCH] =?UTF-8?q?fork=20=E4=B8=80=E4=B8=AA=E8=BF=9B=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/hcsp/shell/Fork.java | 13 +++++++++++++ working-directory/output.txt | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/src/main/java/com/github/hcsp/shell/Fork.java b/src/main/java/com/github/hcsp/shell/Fork.java index 28e0700..6cd8aa0 100644 --- a/src/main/java/com/github/hcsp/shell/Fork.java +++ b/src/main/java/com/github/hcsp/shell/Fork.java @@ -3,6 +3,7 @@ import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Map; public class Fork { public static void main(String[] args) throws Exception { @@ -10,6 +11,18 @@ public static void main(String[] args) throws Exception { // 工作目录是项目目录下的working-directory目录(可以用getWorkingDir()方法得到这个目录对应的File对象) // 传递的命令是sh run.sh // 环境变量是AAA=123 + // 可执行程序 // 2 参数 + ProcessBuilder pb = new ProcessBuilder("sh","run.sh"); + // 工作路径 + pb.directory (getWorkingDir ()); + // 环境变量 + Map envs = pb.environment(); + envs.put ("AAA","123"); + //pb.inheritIO (); + pb.redirectOutput (getOutputFile ()); + pb.start ().waitFor (); + + } private static File getWorkingDir() { diff --git a/working-directory/output.txt b/working-directory/output.txt index e69de29..d3c8754 100644 --- a/working-directory/output.txt +++ b/working-directory/output.txt @@ -0,0 +1,7 @@ +AAA is: 123 +total 40 +-rw-r--r-- 1 a staff 12B Apr 29 09:53 output.txt +drwxr-xr-x 13 a staff 416B Apr 29 09:53 .. +-rw-r--r-- 1 a staff 47B Apr 29 07:38 run.sh +drwxr-xr-x 5 a staff 160B Apr 29 07:38 . +-rw-r--r-- 1 a staff 11K Apr 29 07:38 .hidden.txt