CUPS打印文件分段错误

CUPS print file segmentation fault

我正在尝试制作一个 CUPS 打印系统。我想获取打印机状态,到目前为止打印了多少页等

为此,我正在执行 CUPS 示例中给出的示例程序。

#include <cups/cups.h>
#include <stdio.h>


int main(){

int num_options;
cups_option_t *options;

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);
int job_id;

/* Print a single file */
job_id = cupsPrintFile(dest->name, "testfile.txt", "Test Print", num_options, options);

cupsFreeDests(num_dests, dests);

return 0;
}

我用gcc myfile.c -o myout -lcups

编译

当我尝试执行 ./myout

我得到

Segmentation fault

我正在使用 Raspberry-pi 3 开发板作为我的 CUPS 服务器。

提前致谢。

dest 指向无效地址。

cups_dest_t *dest; // declared but not initialized or assigned afterwards 

因此取消引用它 (cupsPrintFile(dest->name...) 是 UB 并且可能导致 SegFault。


你应该这样使用它(取自here):

#include <cups/cups.h>

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);

/* do something with dest */

cupsFreeDests(num_dests, dests);

更新:

您的代码不处理某些变量(即让它们未初始化 - 不好)。我看到的第一个是cups_option_t *options;。处理所有变量,如果这不起作用 - 调试。

int main(){

int num_options;
cups_option_t *options; // add a call to "cupsAddOption("first", "value", num_options, &options);"

cups_dest_t *dests;
int num_dests = cupsGetDests(&dests);
cups_dest_t *dest = cupsGetDest("name", NULL, num_dests, dests);
int job_id;

/* Print a single file */
job_id = cupsPrintFile(dest->name, "testfile.txt", "Test Print", num_options, options); // options is used here but is uninitialized

cupsFreeDests(num_dests, dests);

return 0;
}