#include #include #include #include int main() { int rc; int fd; printf( "Standard output\n" ); close( 1 ); /* close stdout */ printf( "Standard output?\n" ); /* open a file for writing */ fd = open( "newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0400 | 0200 ); printf( "fd is %d\n", fd ); fprintf( stderr, "(stderr) fd is %d\n", fd ); /* redirect one file descriptor to another */ rc = dup2( fd, 2 ); /* stderr (2) redirected to fd (1) */ /* dup2() closes stderr (2) */ /* rc of dup2() is equal to 2nd arg on success */ if ( rc == 2 ) { /* success */ fprintf( stderr, "(stderr) Where does this error msg go?\n" ); } else { perror( "dup2() failed" ); return 1; } /* FORK A CHILD PROCESS */ { pid_t z = fork(); if ( z == 0 ) { printf( "CHILD: Hey, where's my output going?\n" ); fprintf( stderr, "CHILD: How about my stderr?\n" ); execlp( "/bin/ls", "ls", NULL ); } else /* parent */ { wait( NULL ); } } close( fd ); printf( "CAN WE SEE THIS? (NOPE)\n" ); return 0; }