我正在使用 MAMP(Mac 上也是如此)并使用 C 语言处理 CGI。我编写了以下代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("Content-Type: text/html; charset=utf-8\n\n");
printf("Hello <b> in bold</b>\n");
FILE *f = popen("lp -", "w");
if (!f)
{
printf("<b>ERROR</b>\n");
exit(1);
}
fprintf(f, "This will be send to printer");
return 0;
}
当我在终端下运行它时(当然是在编译之后),我看到文本“Hello in bold”,并且“This will be send to Printer”的输出正确发送到打印机。 但是当我将CGI放在MAMP中的cgi-bin文件夹中并调用CGI时,文本正确显示(意味着CGI正确执行),但没有输出到打印机。 为什么?有什么想法吗?
最佳答案
它有效! 首先非常感谢那些提出意见的人,帮助很大。 我将解释我所做的事情,因为它在解决这个 CGI 问题之外可能很有用。 从 Mac 桌面运行 CGI(问题中的代码)是可以的。作为 CGI 运行不会提供打印机输出,但文本“Hello 粗体”正确显示在网页上。 看看 Apache Erro 日志(尾部位于 Applications/MAMP/logs/apache_error.log),感谢 Antti Haapala,我明白了:
lp\xc2\xa0: erreur - aucune destination par d\xc3\xa9faut disponible.
含义“没有可用的默认目的地”。执行“which lp”(感谢 I'L'I)后,我得到/usr/bin/lp,将其设置在我的 popen() 调用中并运行 CGI。 我进入错误日志:
/usr/bin/lp\xc2\xa0: erreur - aucune destination par d\xc3\xa9faut disponible.
同样的答案...搜索后我发现一个奇怪的点:当我从桌面运行 CGI 时(因此单击它),它使用我在“首选项”面板中设置的默认打印机(EPSON M105)进行打印我的Mac。这意味着当您从桌面使用 popen(lp) 时,它可以工作。但是当您通过 Apache 在 CGI 中使用它时,对于 CGI 来说没有默认打印机,这意味着 Mac OSX 似乎有两个默认打印机设置。 因此,在终端下,我完成了:
lpstat -a
获取可用打印机的列表。然后,只需执行以下操作:
lpoptions -d PRINTERNAME
用从先前命令获得的打印机名称替换“PRINTERNAME”,以设置“lp”的默认打印机。
然后再次运行 CGI。现在,它打印但是......给出内部服务器错误!
再次搜索后,我发现使用 lp 和“w”输出打印机的名称。奇怪的是,似乎输出是在执行 pclose() 时完成的,就好像您不放置 pclose() 一样,您不会遇到错误 500。 要使用 pclose() 并避免此输出,必须在 popen() 中使用“r+”而不是“w”。
好的代码是:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int status;
printf("Content-Type: text/html; charset=utf-8\n\n");
printf("Hello test 7 <b> in bold</b>\n");
FILE *f = popen("lp -", "r+");
if (!f)
{
printf("<b>ERROR</b>\n");
exit(1);
}
fprintf(f, "Text that will be send to the printer");
fflush(f);
status = pclose(f);
printf("Hello <b> in bold 2</b>\n");
return 0;
}
希望这会有所帮助。
关于CGI 无法在 MAMP 下打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822668/