bash redirection question

Bob Bell bbell at hp.com
Fri Nov 7 16:03:07 EST 2003


On Fri, Nov 07, 2003 at 03:40:44PM -0500, Kenny Donahue wrote:
>Here is a simple question (I hope) for all you bash experts.
>
>I have a c program that gathers a bunch of information then writes
>this information to a file.  The c program then calls a bash script with
>the file that was created as an argument.  The bash script sources the
>file and does things according to what was set in the file.
>
>Now the problem. I'd like to use the same log file for the c program
>and the shell script. Since I'm making calls in the script such as insmod,
>rm, lsmod, rmod. etc... I'd like to redirect the output from
>1. My echos
>2. stdio from all system calls
>3. stderr from all system calls
>But still have everything displayed on the screen
>
>I'd like to do this without appending " | tee -a $log_file"
>to everything.
>Any ideas?

Write your bash script to write to stdout (file descriptor 1), for 
simplicity.  Since you are running your bash script from your C code, 
you have control over what "stdout" is for the bash script.  Create 
a pipe(), and before exec()'ing your bash script, use dup2() to replace 
file descriptors 1 and 2 (stdout and stderr) with the write side of the
pipe.  Then, in your C program, while you are "waiting" for your bash 
script to complete, read the script's output from the read side of the 
pipe.  When you read a line of output, you can write it to both the 
screen and to your log file.

No bash magic involved, just some C-fu. :-)

-- 
Bob Bell



More information about the gnhlug-discuss mailing list