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
).
Order of redirections is significant. As you've written it, the order is:
somefile.txt
.What you want is:
somefile.txt
.So use:
popen("cmd 2>&1 >somefile.txt", "r")