Link to home
Start Free TrialLog in
Avatar of zed1
zed1

asked on

redirecting stderr in c

I want to execute a program which outputs to stderr, in a section of c code.  I could use popen() to monitor output, but this only pipes stdout back to the calling program.  I need to read from stderr to recieve update information until the program has finished executing.

How do I do this?
Avatar of zed1
zed1

ASKER

Adjusted points to 200
/*
 * Command program to echo supplied arguments to standard error
 */
#include <stdio.h>
#include <stdlib.h>

main(int argc, char **argv)
{
    /* Skip program name */
    argc--;argv++;

    /* Print remaining arguments, separated by spaces, terminated by newline */
    while (argc--)
        fprintf(stderr,"%s%c", *argv++, argc ? '\n' : ' ' );
}
Avatar of zed1

ASKER

Hmmm...  Perhaps you only read the first sentence of my question.  Sorry for not explaining it well enough.

I want to execute a program using a shell command in c.  The program that I want to execute outputs to stderr.  Using the popen() function, only stdout gets piped back to my program, NOT stderr which is what I need.

If the program outputted to stdout I could simply use the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

      main()
            {
                    char *cmd = "<command>";
                     char buf[BUFSIZ];
                     FILE *ptr;

                    if ((ptr = popen(cmd, "r")) != NULL)
                          while (fgets(buf, BUFSIZ, ptr) != NULL)
                                
                          //each line from stdout gets
                          //put into the buf variable
                return 0;
            }

However, this code wont work for me.

How are you piping the stderr output of your program into your other program?  Are you using "|&" instead of "|" ?
Avatar of ozo
char *cmd = "command 2>&1";
I have not tried this, but let me make a suggestion:
(1) The external program could close or redirect it's standard output and instead write it's stderr to that file descriptor. This could be done by exchanging the file descriptors _iobuf[1]
and _iobuf[2].
(2) If you don't have the source for the external program, you could write a wrapper around it which does the above thing. If you then execute the 'external' prg by calling vfork() (or was it clone(), anyway, so that the new program overlays the old one and inherits all its file descriptors) these settings should remain.
ASKER CERTIFIED SOLUTION
Avatar of dhm
dhm

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zed1

ASKER

Thanx dhm, your solution seems to be working fine.  At first I had a little trouble recieving output from stderr and stdout simultaneously, but all I had to do was alter the while loops in the main.