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

The shell command $ avrdude -c usbtinyprints text to stderr. I cannot read it using commmands such as head-less-more, because it is not stdout. I want the text to be stdout or to a file. How can I do this in C? I tried to solve the problem my last question , but still not resolved.

+5
source share
4 answers

I have not tried something like this on OpenBSD, but at least on a few * nix-like systems, you can do it with 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");
}
+13
source

A normal way would be something like:

avrdude -c usbtiny 2>&1

, stderr, stdout. , - :

avrdude -c usbtiny 2> outputfile.txt
+3

POSIX . stderr stdout POSIX dup2 .

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

int main (void)
{
    pid_t child = fork();

    if (child == 0)
    {
        dup2(STDOUT_FILENO, STDERR_FILENO);
        execlp("avrdude", "-c", "usbtiny", NULL);
    }
    else if (child > 0)
    {
        waitpid(child);
        puts("Done!");
    }
    else
    {
        puts("Error in forking :(");
    }

    return 0;
}
0

- C, stderr

man fork, man exec , . man 7 signal, man sigaction man wait , .

, man dup2.

:

int pip_stderr[2];
int r;
int pid;

r = pipe(pip_stderr);
assert( r != -1 );

int pid = fork();
assert( pid != -1 );
if (pid == 0) { /* child */
   /* child doesn't need to read from stderr */
   r = close(pip_stderr[0]); assert( r != -1 );
   /* make fd 2 to be the writing end of the pipe */
   r = dup2(pip_stderr[1], 2); assert( r != -1 );
   /* close the now redundant writing end of the pipe */
   r = close(pip_stderr[1]); assert( r != -1 );
   /* fire! */
   exec( /* whatever */ );
   assert( !"exec failed!" );
} else { /* parent */
   /* must: close writing end of the pipe */
   r = close( pip_stderr[1] ); assert( r != -1 );

   /* here read from the pip_stderr[0] */

   r = waitpid(pid,0,0); assert( r == pid );
}

dup2(), stderr ( fd 2) . pipe() fork(). fork , EOF.

, , stdio, . popen() , , stderr stdout ( stdout /dev/null ). .

mktemp() (man 3 mktemp) temp, system() stderr temp , system() read temp .

-1

All Articles