代码之家  ›  专栏  ›  技术社区  ›  x-yuri

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

  •  0
  • x-yuri  · 技术社区  · 7 年前

    考虑以下代码:

    #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 ::1 127.0.0.1 connect("[::1]:8000") 结果 EINPROGRESS (自 库xml2 O_NONBLOCK 库xml2 等待它恢复 finish ,导致 POLLOUT | POLLERR | POLLHUP 库xml2 报告 error

    后续 connect("127.0.0.1:8000") 调用成功,所以总之程序成功完成。

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   x-yuri    7 年前

    正如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>