abkds
abkds

Reputation: 1794

Implementation of redirections in shells

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 ?

Upvotes: 2

Views: 64

Answers (1)

pmverma
pmverma

Reputation: 1703

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.

Upvotes: 1

Related Questions