File descriptors?

Consider the following code segment where program is a valid executable file:

1
2
3
4
5
6
7
8
9
10
11
12
      if ( fork() == 0 ) {
        close ( 1 );
        close ( 2 );
        if ( open ( "test.txt", O_WRONLY) == -1 )  
          exit ( 1 );
        if ( open ( "test.txt", O_WRONLY) == -1 )  
          exit ( 1 );

        execl ( "/bin/program", "program", 0 );
        exit ( 1 );
      }
	


Which of the following is true?
A. File descriptor 1 is used for standard input.
B. File descriptor 2 is used for standard output.
C. Both 1) and 2) are true.
D. In the above code, if program writes an error message (via the file descriptor 2), the message will overwrite the data of standard output that had already been written.
E. In the above code, file descriptors 1 and 2 refer to the different files.

I was thinking the answer was C but I'm unsure. I know it can't be E unless I'm wrong?
0 -> stdin
1 -> stdout
2 -> stderr

A: false
B: false
C: A && B
D: false(not to sure)
E: true(95% sure)
Yeah that makes sense. Even found that in my lecture notes. Thanks.I'm still unsure if it's D or E now.
Well lets put D to the test:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

int main()
{
	freopen("redir_stderr", "w+", stderr);
	freopen("redir_stdout", "w+", stdout);
	
	puts("This goes to redir_stdout");
	perror("This goes to redir_stderr");	

	return 0;
}


Looks like E is the correct one.

Writing to the same file (same results):
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

int main()
{
	freopen("redir_stderr", "w+", stderr);
	freopen("redir_stderr", "w+", stdout);
	
	puts("This goes to redir_stdout");
	perror("This goes to redir_stderr");	

	return 0;
}


Not sure if these tests are sufficient though so don't take my code for it
Last edited on
Thanks smac
Topic archived. No new replies allowed.