How to suppress output when using a dynamic library?

I actually have a solution to this problem, but I am wondering if it has a clicker.

I need to upload my utility to the library using dlopen, and then call one of the functions.

Unfortunately, the function outputs a whole bunch of information on STDOUT, and I don’t want this.

I have a solution that is not portable, and I wonder if there is a better, more general solution that I could use.

Here is what I have ( NB : This is C):

/*
 * Structure for retaining information about a stream, sufficient to
 * recreate that stream later on
 */
struct stream_info {
    int fd;
    fpos_t pos;
};
#define STDOUT_INFO 0
#define STDERR_INFO 1

struct stream_info s_info[2];
point_stream_to_null(stdout, &s_info[STDOUT_INFO]);
point_stream_to_null(stderr, &s_info[STDERR_INFO]);

void *output = noisy_function();

reset_stream(stderr, &s_info[STDERR_INFO]);
reset_stream(stdout, &s_info[STDOUT_INFO]);

/*
 * Redirects a stream to null and retains sufficient information to restore the stream to its original location
 *** NB ***
 * Not Portable
 */
void point_stream_to_null(FILE *stream, struct stream_info *info) {
    fflush(stream);
    fgetpos(stream, &(info->pos));
    info->fd = dup(fileno(stream));
    freopen("/dev/null", "w", stream);
}

/*
 * Resets a stream to its original location using the info provided
 */
void reset_stream(FILE *stream, struct stream_info *info) {
    fflush(stream);
    dup2(info->fd, fileno(stream));
    close(info->fd);
    clearerr(stream);
    fsetpos(stream, &(info->pos));
}

Any suggestions?

+5
source share
5 answers

, , , "".

-

#if defined __unix__
#define DEVNULL "/dev/null"
#elif defined _WIN32
#define DEVNULL "nul"
#endif

( , else case, ..) -

FILE *myfile = freopen(DEVNULL, "w", stream);

, .

. "nul" ; . fooobar.com/questions/20110/.... " C/++" .

+2

setvbuf, stdout, . , noisy_function, , . , undefined.

stdout , , .

#include <stdio.h>

#define QUIET_CALL(noisy) { \
    FILE* tmp = stdout;\
    stdout = tmpfile();\
    (noisy);\
    fclose(stdout);\
    stdout = tmp;\
}

int main(){
    QUIET_CALL(printf("blah blah"));
    printf("bloo bloo\n");
    return 0;
}
+2

, freopend , , , C. , stdout.

, , , Unix ( MacOS), Windows - Windows stdout , , * nix .

0

noisy_function ; noisy_function .

, , , stdout, , , , - .

I would close (redirect to /dev/null) standard output, as you do, which is the easiest way to close noisy_function; another solution (still not portable) might have the value forking and give the child process a call noisy_function.

0
source

All Articles