Shell Programming

Every unix program gets 3 open file descriptors at startup

  • 0: stdin, 1:stdout, 2:stderr

  • Most unix tools send output to stdout and provide no way to send to a file

  • If you want to send to a file, use

    • cmd > filename

    and the shell redirects. Tool is not aware of redirection operator

Every process has an array of open files

A file descriptor is an index of said array

  • When you open a file you get the lowest index

close…open

  • Start with 0 1 2 descriptor

  • close(0)

  • fd = open(‘file’, 0)

  • Closes the 0 file and opens a new one in the 0 position

Open…close…dup…close

  • fd = open(“data”)

  • close(0)

  • dupe(fd)

  • close(fd)

  • Create file in 3 position, close 0, dupe 3 into 0, close 3