Definition

  1. File

    • A container to contain data of a file (provides a linear space so that stores the data linearly).
    • Each file has a low-level name (inode number).
  2. Directory

    • An implement directory tree (directory hierarchy).
    • It also has a low level name.
    • It contains a list of file name and inode number pair.

File Operations

open System Call

  • Syntax: int open(const char *pathname, int oflags);
    • O_RDONLY: Read only
    • O_WRONLY: Write only
    • O_RDWR: Read and write.
    • O_CREAT: If the pathname does not exist, create it as a regular file.
    • O_TRUNC: If the file already exists and is a regular file and the access mode allows writing, it will be truncated to length 0.
  • Return:
    • file descriptor which is an integer to access files.

open Process

  • After executing open system call, it undergoes:

    1. The file descriptor specifies the index into File Descriptor Table (FDT) of the process.
    2. The entries of FDT contain pointers to entries in the System File Table (SFT).
    3. When a file is opened, an entry is created in both FDT and SFT.
    4. SFT entry contains information about whether a file is open for read, write, protection, or lock and the file offset.

  • The file descriptor for the created file is 3.

  • Because when a process is created, file descriptor 0, 1, 2 are opened by the default for standard input, output and error.

read System Call

  • Syntax: ssize_t read(int fd, void *buf, size_t count);
    • fd: file descriptor
    • buf: buffer pointer
    • count: the number of bytes to write to
  • Return:
    • the number of bytes it read.

write System Call

  • Syntax: ssize_t write(int fd, const *buf, size_t count);
    • fd: file descriptor
    • buf: buffer pointer
    • count: the number of bytes to write to
  • Return:
    • the number of bytes it write.

lseek System Call

  • Description:
    • An open file has a current offset to determine where the next read or write will begin reading from or writing to within the file.
    • lseek is used to update the current offset explicitly.
  • Syntax: off_t lseek(int fd, off_t offset, int whence);
    • fd: file descriptor
    • offset: position the file offset to particular location within the file
    • whence: determine how the seek is performed
      • SEEK_SET: the offset is set to offset bytes (offset)
      • SEEK_CUR: the offset is set to offset bytes + its current location (offset + current)
      • SEEK_END: the offset is set to offset bytes + the size of the file (offset + the end)

Examples

  1. File Operations:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    char buf[20] = "Hello World!";
    char rbuf1[20];

    // open or create "myfile"
    int fd = open("myfile", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR );

    write(fd, buf, 20); // write buf into fd
    lseek(fd, 0, SEEK_SET); // update the offset to the start
    read(fd, rbuf1, 20); // read the content in fd (buf) and store into rbuf1
    printf("%s\n", rbuf1); // Hello World!

    lseek(fd, 6, SEEK_SET); // update the offset to the start + 6
    read(fd, rbuf2, 20); // read the content and store into rbuf2
    printf("%s\n", rbuf2); // World!

I/O Redirection

Redirection

  1. Redirection

    • it means that the process modifies its File Descriptor Table (FDT) entry so that it points to a different entry in the System File Table (SFT).
  2. Example

    • The command cat reads from a file and echoes to standard output
    • Suppose the myfile contains “Hello World” content, ls -l > myfile command redirects standard output to myfile:
      1
      2
      3
      cat myfile      # output: Hello World
      ls -l > myfile
      cat myfile # execute ls -l
    • Coding
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      /* 6-2-redirection-exec */
      #include <sys/types.h>
      #include <sys/wait.h>
      #include <unistd.h>
      #include <stdio.h>
      #include <stdlib.h>

      main(){
      char *cmd = "ls";
      char *argv[5];
      argv[0] = "ls";
      argv[1] = "-l";
      argv[2] = ">";
      argv[3] = "myfile";
      argv[4] = NULL;

      execvp(cmd, argv);
      return 0;
      }

dup System Call

  • Description:
    dup is a smart function that can duplicate (copy) the file descriptor fd to the lowest-numbered unused file descriptor in the File Descriptor Table (FDT).

  • Syntax: int dup(int fd)

    • fd: file descriptor
  • Return:

    • Success, return a new file descriptor
    • Error, return -1
  • Example:

    • Redirects standard output
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      /* 6-redirection */

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

      int main(){
      char *cmd;
      char *argv[3];

      int fd = open("myfile", O_CREAT |O_TRUNC |O_RDWR, S_IRUSR| S_IWUSR );
      close(1); // Close the stdout
      dup(fd); // Duplicate fd
      close(fd);

      cmd = "ls";
      argv[0] = "ls";
      argv[1] = "-l";
      argv[2] = NULL;
      execvp(cmd, argv);

      return 1;
      }
      1
      cat myfile      # execute ls -l

Processes Communication

pipe System Call

  • Description:
    • Pipes provide a unidirectional interprocess communication channel.
    • A pipe has a read end and a write end.
      • Data is written to the write end of a pipe can be read from the read end of the pipe.
      • If a process attempts to read from an empty pipe, then read() will block until the data is available.
  • Situations:

    • If all file descriptors referring to the write end of a pipe have been closed, then an attempt to read() from the pipe will see end-of-file.
    • If all file descriptors referring to the read end of a pipe have been closed, then a write() will cause a SIGPIPE signal to be generated for all the calling process.
      • If the calling process is ignoring the signal, then write() fails with the error EPIPE.
  • Syntax: int pipe(int* fd);

    • fd[0]: the read end
    • fd[1]: the write end
  • Return:

    • Success: return 0
    • Error: return -1
  • Example:

    • counting the lines of output in executing ls -l
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      /* 7-pipe */

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

      main(){
      int fd[2];
      int ret;
      char *cmd;
      char *argv[3];

      pipe(fd);

      if ((ret=fork()) > 0){
      /*
      Parent Process

      We want to use parent process executes "ls -l", so do redirection
      We want to redirect the standard output to the write end of pipe
      */
      close(1); // close standard output
      dup(fd[1]); // fd[1] is duplicated to standard output
      close(fd[0]);
      close(fd[1]);

      cmd = "ls";
      argv[0] = "ls";
      argv[1] = "-l";
      argv[2] = NULL;
      execvp(cmd, argv);

      }else if(ret == 0){
      /*
      Child Process

      We want to use child process executes "wc -l", so do redirection
      We want to redirect the standard input to the read end of pipe
      to get the input from the parent process
      */
      close(0); // close standard input
      dup(fd[0]); // fd[0] is duplicated to standard input
      close(fd[0]);
      close(fd[1]);

      cmd = "wc";
      argv[0] = "wc";
      argv[1] = "-l";
      argv[2] = NULL;
      execvp(cmd, argv);
      }
      }

Other Operations

fsync Write Immdeiately

  • Description:

    • The file system will buffer writes in memorys for some time, so the write(s) will actually be issued to the storage device, like data lost.
    • fsync system call forces all dirty data written to disk immediately, and returns after all these writes were completed.
  • Syntax: int fsync(int fd)

  • Return:

    • Success: return 0
    • Error: return -1

rename Rename File

  • Syntax: rename(char* old, char* new)

  • Example:

    1
    2
    3
    4
    5
    6
    int fd = open("foo.txt.tmp", O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
    char buffer[20] = "hello";
    write(fd, buffer, sizeof(buffer));
    fsync(fd);
    close(fd);
    rename("foo.txt.tmp", "foo.txt");

fstat Show Information

  • Show the file metadata (the information about the file).

  • Structure:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    struct stat {
    dev_t st_dev; /* ID of device containing file */
    ino_t st_ino; /* inode number */
    mode_t st_mode; /* protection */
    nlink_t st_nlink; /* number of hard links */
    uid_t st_uid; /* user ID of owner */
    gid_t st_gid; /* group ID of owner */
    dev_t st_rdev; /* device ID (if special file) */
    off_t st_size; /* total size, in bytes */
    blksize_t st_blksize; /* blocksize for filesystem I/O */
    blkcnt_t st_blocks; /* number of blocks allocated */
    time_t st_atime; /* time of last access */
    time_t st_mtime; /* time of last modification */
    time_t st_ctime; /* time of last status change */
    };
  • Example:
    1
    2
    echo hello > file   # create and write "hello" into file
    stat file # show the information of file

Directories Operations

  1. Create Directories

    • mkdir system call
    • Make an empty directory, which contains two entries: .(itself) and ..(parent).
  2. Read Directories

    • opendir system call: open directory
    • readdir system call: read directory entries (similar to ls).
  3. Remove Directories

    • rmdir system call
    • It requires the directory is empty.
  • Example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    #include <sys/stat.h>
    #include <assert.h>
    #include <stdio.h>
    #include <dirent.h>

    int main(int argc, char *argv[]){
    DIR *dp = opendir("."); // open current directory
    assert(dp != NULL);
    struct dirent *d;
    while ((d = readdir(dp)) != NULL) // read one directory entry
    {
    // print outthe name and inode number of each file
    printf("%d %s\n", (int) d->d_ino, d->d_name);
    }
    closedir(dp); // close current directory
    return 0;
    }
  • Description:

    • Creare another name in the directory and refer it to the same inode number (same file) of the original file.
    • Noted: Hard link does not really create a file, it just creates a link which linking to the original file.

    • Editting the old file would change the content in new file.

      1
      2
      3
      4
      5
      6
      7
      echo hello > file
      ln file file2 # create a hard link, link file to file2
      echo helloworld > file
      cat file2 # helloworld

      ls -i file file2
      4633749 file 4633749 file2 # they have the same inode value
  • Syntax:

    • system call: link(char* "oldpath", char* "newpath");
    • command: ln oldpath newpath
  • Remove File:

    • That’s why we call unlink to remove file.
      1
      2
      3
      4
      echo hello > file
      ln file file2 # create a hard link, link file2 to file
      rm file # remove file
      cat file2 # file2 can still access the file
  • Description:

    • It can create for a directory (hard link cannot).
      1
      2
      3
      mkdir foo
      ln foo foo1 # ln: foo: Is a directory
      ln -s foo foo1
  • Difference:

    1. File system knows that symbolic link is a third type (different type), so symbolic link does just create a new file.
    2. The size of symbolic link is 4 bytes
      1
      2
      3
      ls -a
      # -rw-r--r-- ... 6 file
      # lrwxr-xr-x ... 4 file2 -> file
  • Remove File:

    • When the original file was removed, symbolic link points nothing
      1
      2
      3
      4
      echo hello > file
      ln -s file file2
      rm file
      cat file2 # cat: file2: No such file or directory