How can I redirect sandard IO handlers of program A, which I have Spawnl:ed from my main program?
This is a discussion on Redirecting stdout, stderr and stdin within the Linux Programming forums, part of the Platform Specific Boards category; How can I redirect sandard IO handlers of program A, which I have Spawnl:ed from my main program?...
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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
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.
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 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.