2

I am studying os from some notes, it gives a simple shell code as follows :

while (1) {
    printf ("$");
    readcommand (command, args);
    // parse user input
    if ((pid = fork ()) == 0) { // child?
       exec (command, args, 0);
    } else if (pid > 0) {
    // parent?
    wait (0);
    // wait for child to terminate
    } else {
    perror ("Failed to fork\n");
    }
}

And says for implementing ls > tmp we need to include the following lines before exec

close (1);
fd = open ("tmp1", O_CREAT|O_WRONLY);
// fd will be 1!

And for ls 2>tmp>tmp we need to include

close(1);
close(2);
fd1 = open ("tmp1", O_CREAT|O_WRONLY);
fd2 = dup (fd1);

Can anyone explain me a little more about file descriptors in a simple sense and what does close(1) and close(2) do. And the input to close is a fd right, and 2 is error so what is close(2) doing ?

5
  • The close looks like it is closing the first file, going to next file closing it. Making variable fd1 open create file (named "tmp1") piped to this file opened in write and read only. create a variable fd2 and duplicate everything into fd2. Does that help?
    – No Time
    Commented May 27, 2014 at 4:28
  • 2
    BTW you're mistaken, what you are implementing here is a shell (the program interpreting the command line), not ls! And open/close/dup is here to implement shell redirections (i.e. program > a_file) Commented May 27, 2014 at 5:51
  • @ThomasMoulard sorry for that i have updated the question
    – abkds
    Commented May 27, 2014 at 6:35
  • and what is the value of fd2 in the end . Is it 2 ?
    – abkds
    Commented May 27, 2014 at 8:10
  • This isn't shell code. It's C. Commented Jun 1, 2014 at 10:37

1 Answer 1

1

Your main question is about close(1) and close(2). Thus I am not going to view all of your code.

When the main function of your program is invoked, it already has three predefined streams open and available for use and their file descriptor are as following, they also are defined as macro.

 *STDIN_FILENO*
This macro has value 0, which is the file descriptor for standard input.

*STDOUT_FILENO*
This macro has value 1, which is the file descriptor for standard output.

*STDERR_FILENO*
This macro has value 2, which is the file descriptor for standard error output. 

So when your close function do close(1), it close standard output and when you do close(2), it close standard error output.

Note: Generally, these file descriptors are not closed until the process is going to be a daemon process.

1
  • The missing piece to still add is that the next open() will be assigned the first available file descriptor, i.e. fd1 (provided of course that you did not also close fd0).
    – tripleee
    Commented Jun 1, 2014 at 10:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.