Java Runtime.getRuntime().exec()似乎正在覆盖$ PATH [英] Java Runtime.getRuntime().exec() appears to be overwriting $PATH

查看:119
本文介绍了Java Runtime.getRuntime().exec()似乎正在覆盖$ PATH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个使某些突变充分性测试自动化的项目,我正在尝试从Java程序内部的源代码中制作GoLang.我已经能够从终端的源代码中获得它,并尝试在Java的Runtime.getRuntime().exec()命令中使用该命令:

For a project to automate some mutation adequacy testing, I'm trying to make GoLang from source from inside a Java program. I have been able to make it from source in the Terminal, and have tried using that command in Java's Runtime.getRuntime().exec() command:

String[] envp = new String[3];
envp[0] = "CC=/usr/bin/clang";
envp[1] = "GOROOT_BOOTSTRAP=/usr/local/go";
envp[2] = "CGO_ENABLED=0";
Runtime.getRuntime().exec("./all.bash", envp, "$HOME/Desktop/go/src");

与此等效的命令在终端中可以正常工作.在Java中运行此代码(并打印输出)可获得以下信息:

The equivalent command to this works fine in the Terminal. Running this code in java (And printing the output) gets the following:

./all.bash
##### Building Go bootstrap tool.
cmd/dist
go tool dist: FAILED: uname -r: exec: "uname": executable file not found in $PATH

因此找不到uname很奇怪.再次,如果我在终端上输入'uname',它可以正常工作.因此,我找到了uname的目录('what uname'给出了'/usr/bin/uname'),并将此命令的$PATH设置为该目录:

So that's weird that it can't find uname. Again, if I enter 'uname' on the Terminal, it works fine. So I found the directory of uname ('which uname' gives '/usr/bin/uname') and set $PATH to that for this command:

String[] envp = new String[4];
envp[0] = "CC=/usr/bin/clang";
envp[1] = "GOROOT_BOOTSTRAP=/usr/local/go";
envp[2] = "CGO_ENABLED=0";
envp[3] = "PATH=/usr/bin";
Runtime.getRuntime().exec("./all.bash", envp, "$HOME/Desktop/go/src");

然后获取输出:

./all.bash
env: bash: No such file or directory

因此,当我设置路径时,它无法在目录中找到该程序.这告诉我,当调用Runtime.getRuntime().exec()时,它将覆盖$PATH成为我传递给它的目录,然后覆盖我给它的环境变量.但是为了使./all.bash工作,我需要两个路径都在$PATH变量中.我该怎么办?

So when I set the path, it can't find the program in the directory. This suggests to me that when Runtime.getRuntime().exec() is called, it overwrites $PATH to be the directory I passed it, then overwrites the environment variables I gave it. But in order for ./all.bash to work, I need both paths to be in the $PATH variable. How can I do this?

在Mac OS X 10.11.6上.

On Mac OS X 10.11.6.

推荐答案

Runtime.exec被

Runtime.exec was replaced by ProcessBuilder twelve years ago, as part of Java 1.5.

它的许多优越功能是可以添加到现有环境中的功能:

Among its many superior features is the ability to add to the existing environment:

ProcessBuilder builder = new ProcessBuilder("./all.bash");
builder.inheritIO();

builder.directory(
    new File(System.getProperty("user.home") + "/Desktop/go/src"));

builder.environment().put("CC", "/usr/bin/clang");
builder.environment().put("GOROOT_BOOTSTRAP", "/usr/local/go");
builder.environment().put("CGO_ENABLED", "0");

builder.start();

这篇关于Java Runtime.getRuntime().exec()似乎正在覆盖$ PATH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆