How can I redirect sandard IO handlers of program A, which I have Spawnl:ed from my main program?
Printable View
How can I redirect sandard IO handlers of program A, which I have Spawnl:ed from my main program?
open()
dup()
close()
Read about those functions in the manual pages.
This is what I do in C:
Remember too,Code:#include <stdio.h>
freopen( "stdin.log", "w", stdin );
freopen( "stdout.log", "w", stdout );
freopen( "stderr.log", "w", stderr );
w+,w - If you want your older contents from the log files to be discarded. Creates text file if not already there.
r+ - If you want to start writing in the logs from the beginning of the file. Opens for update so the text files must already exist.
a+,a - If you want to start writing the logs from the end of the file. Text files must already exist.
This is an example:
This is the output:Code:#include <stdlib.h>
#include <stdio.h>
int main( void )
{
/* Variables
in=UserINPUT */
char *in = malloc( 20 * sizeof( char ) );
/* Setup the streams */
/*freopen( "stdin.log", "w", stdin ); This messes up fgets :( */
freopen( "stderr.log", "w", stderr );
freopen( "stdout.log", "w", stdout );
/* Send the streams some text */
fprintf( stdout, "This is stdout\n" );
fprintf( stderr, "This is stderr\n" );
/*fprintf( stdin, "This should not work" ); This messes up fgets :( */
/* Send stdin some good ol' user text */
fgets( in, 20, stdin );
/* Echo out user input */
puts( in );
/* Return success */
return 0;
}
Code:psycho@Shiva:~/Programming/Laboratory$ gcc -pedantic -ansi -Wall freopen.c
psycho@Shiva:~/Programming/Laboratory$ ./a.out
hello
psycho@Shiva:~/Programming/Laboratory$ cat stdout.log
This is stdout
hello
psycho@Shiva:~/Programming/Laboratory$ cat stderr.log
This is stderr
You could just close em... ...but that's ugly, if you wanna reuse them later.
If you opt for the dup(fd fd2 ) route consider dup2(fd fd1, fd fdnew ) as it's atomic- if it fails it doesn't close try to close fdnew (if it is in use) to create the file descriptor.
wtf are you talking about jim? Are you on crack?
In unix dup2 is an atomic (guaranteed not to be interrupted) call - this is generally a better choice than dup. ... see Rochkind 'Advanced Unix Programming' p 371.
A lot of unix C programmers use freopen() to redirect, FWIW.
I see :]
I think in text mode a/a+, the file is created if it doesn't exist.
You are right dwks, a and a+ create the file if not already created.