Redirecting output from an external C-lib printing to stdout/stderr?

I have a closed source C library my Linux application depends on.

This library isn’t particularly well designed, and most of the functions in it print a bunch of junk to stdout and stderr as a side effect. Sometimes this is useful for debugging, but most of the time I’d like to discard it.

Is there any way for me to “capture” stdout/stderr on those function calls only, while keeping it available for the main program?

In C I’ve used a strategy with dup/dup2 before, something like this where the file descriptors are temporariliy redirected somewhere else.

Does Zig have a better way?

In principle you could wrap the library calls so that you dup2() before the syscall and then again after the call to restore the original file descriptor… :nauseated_face:

1 Like

You could also try to mix running the library on a separate process, with using dup2 to change where stdout / stderr go for that process. Hard to say if this is doable in your case without more details.

This is in fact what I ended up doing. I don’t like it, but I don’t think there’s a better way. If the code I’m interfacing with was well-made I wouldn’t need it in the first place, but such is life sometimes when you’re dealing with proprietary legacy bullshit.

At least Zig’s defer keyword makes it relatively clean. I have a redirect(output fd) and a restore(output fd) function that perform the operations with dup2.

Call the redirect function at the beginning of a scope, defer the restore, then continue as usual.