views:

641

answers:

5

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.

A: 

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

Michiel Buddingh'
equiv: NUL on windows
streetpc
A: 

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

./myProgram 2>/dev/null

Ambuoroko
Which is what he specifically didn't ask for.
David Thornley
I was not clear on what he meant by a "redirecting shell script".
Ambuoroko
+11  A: 

Use freopen to redirect to dev/null:

freopen("/dev/null", "w", stderr);
Robert
Beat me by 10 seconds!
Byron Whitlock
+9  A: 

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()

laalto
Thanks I'll use it in the future, but I need a quick solution right now, so freopen will do for now.
+2  A: 

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 <sts/stat.h>
#include <fcntl.h>
#include <unistd.h>

...

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