Lectures‎ > ‎

Week05


I/O Redirection

  • How does the shell do
    • date > out
  • The quick answer:
    • We modify the file descriptor table
  • We need to take a closer look at how the file descriptor table works


File Descriptor Table (FD Table)

  • Each Process has a file descriptor table in the kernel (in the Process Control Block)
  • fork() duplicates the file descriptor table
  • Draw picture of two file descriptor tables with stdin, stdout, stderr.


Modifying the FD Table

  • In order to redirect input/output, we need to modify the file descriptor table
  • New system call:
    • int dup(int oldfd)
    • Makes a copy of the given fd in the first available fd table slot
  • We can use close() to open up slots


Redirection Example

redirect.c

/* redirect.c - example of redirection */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
	pid_t id;
	int fd;

	if ((fd = open("out", O_CREAT | O_WRONLY, 0644)) < 0) {
	    printf("cannot open out\n");
	    exit(1);
	}

	id = fork();

	if (id == 0) {
        /* we are in the child */
        /* close stdout in child */
        close(1);
        dup(fd);   /* replace stdout in child with "out" */
        close(fd);
        execl("/bin/date", "date", NULL);
	}

	/* we are in the parent */
	close(fd);
	id = wait(NULL);

	return 0;
}

Comments