How to make libxml2 not display connection errors?

2019-08-20 09:40发布

Consider the following code:

#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;
}

The output:

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

That is, xmlParseFile produces undesired output. What happens here is libxml2 tries to translate localhost to IP address. What it gets is ::1 and 127.0.0.1. connect("[::1]:8000") results in EINPROGRESS (since libxml2 sets O_NONBLOCK on the descriptor). So libxml2 waits for it to finish, which results in POLLOUT | POLLERR | POLLHUP, and libxml2 reports an error.

Subsequent connect("127.0.0.1:8000") call succeeds, so all in all the program finishes successfully.

Is there a way to avoid this extra output?

标签: c libxml2
1条回答
Explosion°爆炸
2楼-- · 2019-08-20 10:18

As suggested by nwellnhof, connection errors can be circumvented by setting error handler. Particularly, structured error handler, whatever that means.

While the answer in the other question more or less answers my question, that other question is about parser errors. And the answer doesn't provide example code. So,

#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;
}

This one outputs,

xmlStructuredErrorFunc
<result of xmlNodeGetContent>
查看更多
登录 后发表回答