Skip to content

Instantly share code, notes, and snippets.

@detunized
Created October 15, 2012 08:42
Show Gist options
  • Save detunized/3891486 to your computer and use it in GitHub Desktop.
Save detunized/3891486 to your computer and use it in GitHub Desktop.
Redirect stderr into a pipe, filter and then write to stdout (for NSLog filtering)
int main(int argc, char *argv[])
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^(void) {
size_t const BUFFER_SIZE = 2048;
// Create a pipe
int pipe_in_out[2];
if (pipe(pipe_in_out) == -1)
return;
// Connect the 'in' end of the pipe to the stderr
if (dup2(pipe_in_out[1], STDERR_FILENO) == -1)
return;
char *buffer = malloc(BUFFER_SIZE);
if (buffer == 0)
return;
for (;;)
{
// Read from the 'out' end of the pipe
ssize_t bytes_read = read(pipe_in_out[0], buffer, BUFFER_SIZE);
if (bytes_read <= 0)
break;
// Filter and print to stdout
if (should_show(buffer)) // TODO: Apply filters here
fwrite(buffer, 1, bytes_read, stdout);
}
free(buffer);
close(pipe_in_out[1]);
});
// Rest of main
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment