我正在运行shell script
和C
应用to allow execution as root
的混合体。我正在使用它来使用FontForge
中编写的网站PHP
进行一些转换。我的问题是,当FontForge遇到一些问题时,它的喷出错误信息输出到标准输出。我目前正在捕获该输出并解析它以获取关键字以生成一些错误消息。
我不是很熟悉C或shell脚本,所以请不要笑:)。这就是我所拥有的:
PHP:
[...]
$new_path = exec("./convert_font " . $file . " " . $file2);
if (strpos($new_path, 'Save Failed') !== false) {
// throw exception or something
}
[...]
脚本(convert_font):
#!/bin/bash
PATH=/usr/local/bin:$PATH
FONTFORGE_LANGUAGE=ff
export PATH FONTFORGE_LANGUAGE
if (test -f $1);
then
a=$(./pfb2otf $1 $2 2>&1)
fi
echo $a
C(pfb2otf):
#!/usr/bin/fontforge
//Opens file
Open($1);
Reencode("unicode");
//Makes conversion to otf
Generate($2+".otf");
//Prints the resulting name (if conversion is successful) to STD_OUT so I can capture it with my bash script to send back to PHP and consider operation successful to
Print($2+".otf");
Quit(0);
答案 0 :(得分:1)
http://php.net/manual/en/function.exec.php
<强>输出强>
如果输出参数存在,那么指定的数组将被命令的每一行输出填充。尾随空格(例如\ n)不包含在此数组中。请注意,如果数组已包含某些元素,则exec()将附加到数组的末尾。如果您不希望函数附加元素,请在将数组传递给exec()之前调用数组上的unset()。
您可以使用PHP代码中的附加输出参数来捕获数组的所有stdout消息。您还可以在perl和C
中将stderr重定向到stdouthttp://www.masaokitamura.com/2009/08/how-to-redirect-stderr-to-stdout-in-perl/
希望这有帮助。
答案 1 :(得分:1)
有三点需要注意:
1)您的程序可能会在错误输出上写入错误,为了获取它们,您需要添加2>&1
$new_path = exec("./convert_font " . $file . " " . $file2 . ' 2>&1');
2)exec()只返回命令执行的最后一行,获取返回值的最安全方法是将第二个参数传递给exec()。
$return = array();
exec("./convert_font " . $file . " " . $file2 . ' 2>&1', $return);
您可能会注意到$ return是一个包含1行/条目的多维数组。因此,为了确保将错误输入此数组,您可以执行以下操作:
$new_path = implode("", $return);
3)如果你的某个文件有空格(至少)或后引号/括号/美元(...... shell可以解释的所有内容),请不要忘记使用escapeshellarg。
$return = array();
exec("./convert_font " . escapeshellarg($file) . " " . escapeshellarg($file2) . ' 2>&1', $return);