Search code examples
cshpopen

Redirect (stderr of redirect) to stdout


The title is slightly confusing, because this might be an XY problem.

I am aware that 2&>1 will redirect the stderr of a program to stdout.

Here's my problem. I'm trying to do this:

popen("echo Y > /sys/class/.../somefile.txt", "r")

And detect if the command fails. I know if the command fails from the CLI if I see the following on stderr:

-sh: echo: write error: Device or resource busy

However, I can't seem to capture this output no matter what I try.

If I do popen("echo Y > /sys/class/.../somefile.txt 2&>1", "r") it simply redirects the original echo statement's stderr to stdout, not the stderr of the redirect operation. In that case, how can I detect if the command has failed? I also tried examining the return code of pclose but that doesn't seem to change either (always 0).


Solution

  • Order of redirections is significant. As you've written it, the order is:

    1. Redirect stdout to somefile.txt.
    2. Redirect stderr to whatever stdout is now.

    What you want is:

    1. Redirect stderr to the original stdout.
    2. Redirect stdout to somefile.txt.

    So use:

    popen("cmd 2>&1 >somefile.txt", "r")