[10/17/2011] Addendum to 10/14/2011 notes, in preparation for the Midterm Exam.... ===================================================================== Here's Sample Question #2 again -- note the comments showing how the file descriptor changes as close() and dup2() are called. /* SAMPLE QUESTION #2 */ #include #include /* FILE DESCRIPTOR TABLE: * +---------+ * 0 | stdin | * +---------+ * 1 | stdout | * +---------+ * 2 | stderr | * +---------+ */ int main() { int rc; printf( "ONE\n" ); fprintf( stderr, "ERROR: ONE\n" ); rc = close( 1 ); /* FILE DESCRIPTOR TABLE: * +---------+ * 0 | stdin | * +---------+ * 1 | | * +---------+ * 2 | stderr | * +---------+ */ printf( "TWO\n" ); fprintf( stderr, "ERROR: TWO\n" ); rc = dup2( 2, 1 ); /* FILE DESCRIPTOR TABLE: * +---------+ * 0 | stdin | * +---------+ * 1 | stderr | * +---------+ * 2 | stderr | * +---------+ * * dup2() copied entry for fd 2 to fd 1 */ printf( "THREE\n" ); fprintf( stderr, "ERROR: THREE\n" ); close( 2 ); /* FILE DESCRIPTOR TABLE: * +---------+ * 0 | stdin | * +---------+ * 1 | stderr | * +---------+ * 2 | | * +---------+ * * At this point, anything going to stdout via printf() * is redirected to stderr (so it also appears as part * of this program's output) */ printf( "FOUR\n" ); fprintf( stderr, "ERROR: FOUR\n" ); return 0; } ===================================================================== Note the correction to the comment after close( 1 ) and close( 2 ). Though stdout is buffered, stderr is not. This will be irrelevant on the Midterm Exam. /* SAMPLE QUESTION #4 */ #include #include #include #include int main() { int rc; close( 1 ); /* closing this descriptor only "hides" the output */ close( 2 ); /* any printf() output is still in mem until */ /* fflush() flushes it away. NOTE that this is */ /* not true of stderr, though! No buffering */ /* of stderr occurs. */ printf( "HI\n" ); /* fflush( stdout ); */ fprintf( stderr, "ERROR\n" ); open( "newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600 ); printf( "WHAT?\n" ); /* fflush( stdout ); */ fprintf( stderr, "ERROR AGAIN\n" ); rc = fork(); if ( rc == 0 ) { printf( "AGAIN?\n" ); fprintf( stderr, "ERROR ERROR\n" ); } else { wait( NULL ); } printf( "BYE\n" ); fprintf( stderr, "HELLO\n" ); return 0; }