Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: how to redirect stderr from System-command to stdout or file?

The shell command $ avrdude -c usbtiny outputs text to stderr. I cannot read it with commmands such as head-less-more cos it is not stdout. I want the text to stdout or to a file. How can I do it in C? I have tried to solve the problem by my last question but still unsolved.

like image 879
otto Avatar asked Jun 11 '10 01:06

otto


People also ask

How do I redirect stderr and STDOUT to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.

How would you redirect a command stderr to STDOUT?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


2 Answers

I've not tried something like this in OpenBSD, but in at least a few *nix-like systems, you can do this using dup2.

#include <unistd.h>
#include <stdio.h>

int main(void) {  

  fprintf(stderr, "This goes to stderr\n");

  dup2(1, 2);  //redirects stderr to stdout below this line.

  fprintf(stderr, "This goes to stdout\n");
}
like image 117
Dusty Avatar answered Oct 11 '22 11:10

Dusty


The normal way would be something like:

avrdude -c usbtiny 2>&1

This directs what would normally go to stderr to go to stdout instead. If you'd prefer to direct it to a file, you could do something like:

avrdude -c usbtiny 2> outputfile.txt
like image 33
Jerry Coffin Avatar answered Oct 11 '22 10:10

Jerry Coffin