Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/main/java/com/github/hcsp/shell/Fork.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
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 {
// 请在这里使用Java代码fork一个子进程,将fork的子进程的标准输出重定向到指定文件:工作目录下名为output.txt的文件
// 工作目录是项目目录下的working-directory目录(可以用getWorkingDir()方法得到这个目录对应的File对象)
// 传递的命令是sh run.sh
// 环境变量是AAA=123

ProcessBuilder p = new ProcessBuilder("sh", "run.sh");
p.directory(getWorkingDir());
Map<String, String> envs = p.environment();
envs.put("AAA", "123");
p.redirectOutput(getOutputFile());
p.start().waitFor();
}

private static File getWorkingDir() {
Expand Down
7 changes: 7 additions & 0 deletions working-directory/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
AAA is: 123
total 40
-rw-r--r-- 1 a staff 12B Oct 20 08:44 output.txt
drwxr-xr-x 12 a staff 384B Oct 20 08:44 ..
-rw-r--r-- 1 a staff 47B Oct 19 17:33 run.sh
drwxr-xr-x 5 a staff 160B Oct 19 17:33 .
-rw-r--r-- 1 a staff 11K Oct 19 17:33 .hidden.txt