如何使libxml2不显示连接错误?

时间:2018-09-08 08:08:38

标签: c libxml2

考虑以下代码:

#include <stdio.h>
#include <libxml/parser.h>
int main(void) {
    xmlDocPtr doc;
    xmlChar *s;
    doc = xmlParseFile("http://localhost:8000/sitemap.xml");
    s = xmlNodeGetContent((struct _xmlNode *)doc);
    printf("%s\n", s);
    return 0;
}

输出:

$ gcc -g3 -O0 $(xml2-config --cflags --libs) 1.c
$ ./a.out
error : Operation in progress
<result of xmlNodeGetContent>

也就是说,xmlParseFile会产生不希望的输出。这里发生的是libxml2尝试translate localhost到IP地址。它得到的是::1127.0.0.1connect("[::1]:8000")产生EINPROGRESS(因为在描述符上libxml2设置了O_NONBLOCK)。因此,libxml2等待到达finish,结果为POLLOUT | POLLERR | POLLHUP,并且libxml2报告error

随后的connect("127.0.0.1:8000")调用成功,因此所有程序均成功完成。

有没有办法避免这种额外的输出?

1 个答案:

答案 0 :(得分:0)

如nwellnhof所建议,可以通过设置错误处理程序来规避连接错误。特别是结构化错误处理程序,无论其含义是什么。

在另一个问题中的the answer或多或少地回答了我的问题时,另一个问题是关于解析器错误。而且答案没有提供示例代码。所以,

#include <stdio.h>
#include <libxml/parser.h>

void structuredErrorFunc(void *userData, xmlErrorPtr error) {
    printf("xmlStructuredErrorFunc\n");
}

void genericErrorFunc(void *ctx, const char * msg, ...) {
    printf("xmlGenericErrorFunc\n");
}

int main(void) {
    xmlDocPtr doc;
    xmlChar *s;
    xmlSetGenericErrorFunc(NULL, genericErrorFunc);
    xmlSetStructuredErrorFunc(NULL, structuredErrorFunc);
    doc = xmlParseFile("http://localhost:8000/sitemap.xml");
    s = xmlNodeGetContent((struct _xmlNode *)doc);
    printf("%s\n", s);
    return 0;
}

这一个输出,

xmlStructuredErrorFunc
<result of xmlNodeGetContent>