我正在尝试从 tomcat 7 上的 java servlet 调用 perl 脚本。我已经设置了 context.xml 和 web.xml,因此我可以通过转到 http://localhost:8080/test/cgi-bin/test.pl 来运行 .pl 文件。我还可以直接在 java 中运行 perl,如下所示:
String[] cmdArr = new String[]{"perl", "-e", "print \"Content-type: text/html\n\n\";$now = localtime();print \"<h1>It is $now</h1>\";"};
if (cmdArr != null) {
Process p = null;
Runtime rt = Runtime.getRuntime();
try {
p = rt.exec(cmdArr); // throws IOException
returnValue = p.waitFor(); // throws InterruptedException
}
catch (IOException xIo) {
throw new RuntimeException("Error executing command.",xIo);
}
catch (InterruptedException xInterrupted) {
throw new RuntimeException("Command execution interrupted.",xInterrupted);
}
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader stdout = null;
stdout = new BufferedReader(isr);
String line = null;
try {
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException xIo) {
throw new RuntimeException("Error reading process output", xIo);
}
}
这工作正常,但如果我尝试通过替换以下内容来引用我的/WEB-INF/cgi 文件夹中的 .pl 脚本:
String[] cmdArr = new String[]{"perl", "-e", "print \"Content-type: text/html\n\n\";$now = localtime();print \"<h1>It is $now</h1>\";"};
类似:
String cmdArr = "/WEB-INF/cgi/test.pl";
或
String cmdArr = "/cgi-bin/test.pl";
我不断收到此错误:
java.io.IOException: Cannot run program "/WEB-INF/cgi/test.pl": error=2, No such file or directory
我猜我的文件路径在某个地方出了问题?任何帮助将不胜感激!
<小时/>更新:
在 @hobbs 评论后,我更改为: String[] cmdArr = new String[]{"perl", "/WEB-INF/cgi/test.pl"};
但是如果我在 .waitFor() 之前添加以下内容:
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ( (line = br.readLine()) != null){
System.out.println(line);
}
我得到打印:
Can't open perl script "/WEB-INF/cgi/test.pl": No such file or directory
我想这又回到了最初的问题?
最佳答案
有点令人困惑的是,当 exec 系统调用在脚本上返回“没有这样的文件或目录”时,通常意味着无法找到 shebang 行上的解释器。例如如果/WEB-INF/cgi-test.pl 以 #!/usr/bin/perl
开头,那么/usr/bin/perl 可能不存在。或者,如果文件具有 Windows 行结尾,则可能会导致内核寻找名为 "/usr/bin/perl\x0a"
的解释器,但找不到。
既然您已经确定可以使用以 "perl"
开头的命令数组来运行事物,那么:
String cmdArr = new String[]{"perl", "/WEB-INF/cgi/test.pl"};
?
关于java - 从 Java servlet 调用 perl 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7716946/