The static library performs some operations and outputs to "stderr" if
an error is occured. I want to log the messages in stderr in the main
library. However, when I try to read stderr as given below:
char buffer[4096];
fscanf(stderr, "%s", buffer);
First up, unless you're *sure* that the messages produced by the library
won't exceed 4096 bytes, an unbounded string scan like this could lead
to a buffer overflow.
I get strange characters in the buffer, not the message. However, when
I quick watch stderr, I see the message in stderr->_base member.
What am I doing wrong? Thanks.
As people have said, this is difficult to do portably.
One solution on POSIX-like systems would be to use an anonymous pipe to
temporarily replace stderr's file descriptor. Here is some example code
to give you the idea:
#include <stdio.h>
#include <unistd.h>
void some_library_function(void)
{
fputs("hello!\n", stderr);
}
int main(void)
{
int stderr_backup, pipefd[2];
char buf[4096];
if(pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
if((stderr_backup = dup(STDERR_FILENO)) == -1) {
perror("dup");
return 1;
}
if(dup2(pipefd[1], STDERR_FILENO) == -1) {
perror("dup2");
return 1;
}
some_library_function();
if(read(pipefd[0], buf, sizeof(buf)) == -1) {
perror("read");
return 1;
}
buf[sizeof(buf)-1]='\0';
printf("read from stderr: %s", buf);
close(pipefd[0]);
close(pipefd[1]);
if(dup2(stderr_backup, STDERR_FILENO) == -1) {
perror("dup2");
return 1;
}
puts("== original stderr now restored ==");
some_library_function();
return 0;
}