【问题标题】:Runtime.exec() can't run "su - postgres -c 'pg_dump ...'"Runtime.exec() 无法运行“su - postgres -c 'pg_dump ...'”
【发布时间】:2010-12-30 17:10:31
【问题描述】:

这是我要运行的命令:

su - postgres -c "pg_dump ....."

备份 postgres 数据库。

如果我现在在 linux shell 中,以 root 身份,它工作得很好。

但现在,我想从 java 应用程序中运行它,如下所示:

String cmd = "su - postgres -c \"pg_dump --port 5432 .....\""
Process p = Runtime.getRuntime().exec(cmd);
// read the error stream and input stream
p.waitFor();

它会抛出一个错误:

su: unknown option "--port"
please try "su --help" to get more information

现在我将代码更改为:

Process p = Runtime.getRuntime().exec(new String[0]{cmd});
// read the error stream and input stream
p.waitFor();

Cannot run program "su - postgres -c \"pg_dump .....\"": java.io.IOException: error=2, no that file or directory

我现在该怎么办?

【问题讨论】:

    标签: java linux runtime.exec


    【解决方案1】:

    除了上面给出的答案(理解你的问题很好)之外,请记住,只需将命令放在 shell 脚本文件中,你总是可以让你的生活更轻松。例如,一个只包含两行的dumppg.sh 文件:

    #!/bin/sh
    su - postgres -c "pg_dump ....."
    

    只需使其可执行,并(在测试后)从 java 调用它。

    【讨论】:

    • 我不得不说,这是最简单的方法。谢谢
    【解决方案2】:
    exec(new String[]{"sh", "-c", "su - postgres ..."});
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 2016-03-26
      • 2019-06-25
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      相关资源
      最近更新 更多