有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

linux如何使用java程序执行oraenv脚本?

如何使用java程序执行oraenv脚本?如何从Linux终端执行

 [oracle@DeltaLinOraASM2 tmp]$ . oraenv
 ORACLE_SID = [oracle] ? deltaasm
 The Oracle base has been set to /u01/app/oracle
 [oracle@DeltaLinOraASM2 tmp]$

我的oraenv脚本文件包含以下内容:

export ORACLE_HOME=/opt/oracle/product/12.2.0.1/dbhome_1
export PATH=$PATH:$ORACLE_HOME/bin
export ORACLE_SID=deltaasm

如何使用java程序执行oraenv文件

它正在询问ORACLE_SID=?在执行脚本之后。但从程序上看,它并没有被执行

public class App2 {

public static String RunLinuxGrepCommand(String command) {
    String line = null;
    String strstatus = "";
    try {

        String[] cmd = { "/bin/sh", "-c", command };
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = in.readLine()) != null) {
            strstatus = line;
        }
        in.close();
    } catch (Exception e) {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        String stackTrace = sw.toString();
        int lenoferrorstr = stackTrace.length();
        if (lenoferrorstr > 500) {
            strstatus = "Error:" + stackTrace.substring(0, 500);
        } else {
            strstatus = "Error:" + stackTrace.substring(0, lenoferrorstr - 1);

        }
    }
    System.out.println("strstatus" + strstatus);
    return strstatus;

}

public static void main(String[] args) throws IOException {

    String str = ". oraenv ; deltaasm ";
    App2.RunLinuxGrepCommand(str);

}
}

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    您需要了解在Java中使用exec时会发生什么:

    1. 创建了一个新的外部流程
    2. 进程将执行您发出的命令
    3. 过程退出

    例如,如果你这样做:

      exec(". oraenv");
      exec("someOracleCommand");
    

    将会发生的是:

    1. 首先创建流程
    2. 第一个进程为该进程执行“.oraenv”设置环境变量
    3. 第一个进程退出
    4. 创建第二个进程
    5. 第二个进程使用默认环境执行“someOracleCommand”
    6. 第二个进程退出

    看到问题了吗?环境变量设置不会从第一个进程传递到第二个进程

    实际上,我上面说的是不真实的。像那样运行“.oraenv”在任何情况下都不起作用。“那个”命令是shell内置的,除非运行shell,否则不可用。但上面所说的并没有做到。{}将失败

    解决方案:您需要在同一个shell中运行. oraenv和命令,如下所示:

      exec("/bin/bash", "-c",
           ". oraenv ; someOracleCommand");
    

    我们所做的是将shell命令序列放在一行中,并将其传递给shell执行。shell知道如何解析命令序列。。。并将在shell的环境中设置环境变量,以便它们可用于在shell中运行的以下命令