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 ?
program > a_file
)fd2
in the end . Is it 2 ?