Question

I wrote a program for linux using libxml2 for html parsing. Although it does its job, the html parser writes lots of various errors to stderr. Is it possible to disable stderr at all (or redirect it to /dev/null while not having to run it with a redirecting shell script)? I can live with having to write my own errors to stdout, I just want to get rid of these errors.

Was it helpful?

Solution

Use freopen to redirect to dev/null:

freopen("/dev/null", "w", stderr);

OTHER TIPS

freopen()ing stderr has already been mentioned, which addresses your specific question. But since you're working with libxml2, you may want finer grained control of the error messages and not just redirect all stderr messages categorically. The error messages are there for a reason, you know. See libxml2 documentation on how to use error handlers with libxml2. A good starting point is xmlSetGenericErrorFunc()

freopen(3) is a C-oriented solution (not C++ as the question asked for), and it is just luck that makes it work. It is not specified to work. It only works because when file descriptor 2 is closed and /dev/null is opened, it gets file descriptor 2. In a multi-threaded environment, this may fail. You also cannot guarantee that the implementation of freopen(3) first closes the given stream before opening the new file. This is all assuming that you cannot assume that libxml2 uses C-style stdio.

A POSIX solution to this is to use open(2) and dup2(2):

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

...

/* error checking elided for brevity */
int fd = ::open("/dev/null", O_WRONLY);
::dup2(fd, 2);
::close(fd);

See the manual page for the pipe(2) function. Pass it STDERR and a handle to /dev/null, and it should work.

You can redirect stderr (in bash, anyhow) from the command line as such:

./myProgram 2>/dev/null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top