A piece of code ties stdout to a file in C using freopen. After this piece of code, a script is executed which launches a shell. The problem is now that all stdout output is going into that file, so any commands run in that shell are being placed in that file.
I've arrived at this script that launches the shell:
/bin/sh 1>&2 2>&1
Although it prints to the screen, I am not sure how I can verify that it is actually printing to stdout vs stderr. Can someone verify that I've gotten the IO redirection right?
EDIT: I do not have access to the program that calls freopen, just the script to run.
Your shell fragment:
1
) go to the place where standard error (2
) is currently going; and2
) go to the place where standard output (1
) is currently going.The second operation is not needed.
Original answer
More seriously, if the piece of code is invoked with its standard error going to a file, then the shell's output is going to go to the same file. If you really want it to go to the same place as the original standard output, you need to preserve the original standard output before redirecting with
freopen()
. You'd do that with:Revised answer
Given the scenario:
freopen()
on standard output)/bin/sh 1>&2 2>&1
notation)And assuming you want the standard output of the interactive shell to go to the original standard output, then you can do this with the following code:
launch.sh
Runs Program-A with extra I/O redirections and environment variables set:
The
fd
program printso
for a file descriptor that's open and a-
for a file descriptor that's closed. The-n 32
specifies 'print status for first 32 file descriptors' (by default, it prints for all possible file descriptors, but hundreds of lines consisting of 64 dashes is very boring to read).Program-A
Shell script simulating your non-modifiable program. It runs Program-B after changing standard output to go to a file (
standard.output
).(You could, if you preferred, remove the last
exec
and then echo something afterProgram-B
exits.)Program-B
This is your revised script — the program run by
Program-A
:(Again, it would be possible to delete the final
exec
and do something else afterwards in the script.)The
-i
option invokes an interactive shell. The2>&1
redirects standard error to the same place that standard output is going. The interactive shell prompts on standard error (as I found out again the hard way — though I'd come across the behaviour before).Example runs
The
isodate
command is equivalent todate +'%Y-%m-%d %H:%M:%S'
. My standard prompt on machineosiris
isOsiris JL:
.Without standard error redirected to a file:
With standard error redirected to a file: