プロが教えるわが家の防犯対策術!

javaアプリケーションからcatコマンドを実行し、その結果を取得したいのですが、うまくいきません。runtime.exec()実行中にエラーとなります。

String cmd = "cat error.log; echo $status";
Runtime runtime = Runtime.getRuntime;
Process process = runtime.exec(cmd);

rshを使うとOKです。
"rsh localhost cat error.log; echo $status"

shを使うとNGです。
"sh -c cat error.log; echo $status"
"sh -c \"cat error.log\"; echo $status"

ターミナルからは上記で内容取得、および、結果取得はできるのですが。
環境は、UNIX JDK1.2.1です。
よろしくお願いします。

A 回答 (1件)

多分、実行しているシェルがなんであるか、が分かっていないことが原因


でしょう。

$status って、csh 系のシェルにおいて最近のコマンドの終了状態を格納
しておくシェル変数ですから。

実行結果を取得したいだけであれば、パイプを使わなくとも Process に
該当するメソッドがあります。

こんな感じ。

Process proc = Runtime.getRuntime().exec(new String("cat error.log"));
proc.waitFor();
System.out.println(proc.exitValue());
    • good
    • 0
この回答へのお礼

ありがとうございます。
そのようですね。
いろんなことを一緒に考えてしまいました。

String[] cmd = {"rsh","hostname","cat filename;echo $status"};
Process proc = Runtime.getRuntime().exec(cmd);
結果:出力の最終行

String[] cmd = {"cat","filename"};
Process proc = Runtime.getRuntime().exec(cmd);
int res = proc.exitValue();
結果:res

ですね。

お礼日時:2001/10/08 21:32

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!