UNIX File I/O

File I/O system calls

open

Example (taken from man open in Linux):

#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *pathname = "/tmp/file";
...
fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
...

Another example – creating a lock file:

fd = open("/var/run/myprog.pid", O_WRONLY | O_CREAT | O_EXCL, 0644);

creat

Redundant: creat(path, mode) is equivalent to open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)

And it should have been called create, says Ken Thompson

close

int close(int fildes);

lseek

off_t lseek(int fildes, off_t offset, int whence);

read

ssize_t read(int fildes, void *buf, size_t nbyte);

Note:

write

ssize_t write(int fildes, const void *buf, size_t nbyte);

Note:

Signals and system calls (revisited)

Recall shell2.c from previous lecture:

#include "apue.h"
#include <sys/wait.h>

static void sig_int(int);       /* our signal-catching function */

int
main(void)
{
        char    buf[MAXLINE];   /* from apue.h */
        pid_t   pid;
        int     status;

        if (signal(SIGINT, sig_int) == SIG_ERR)
                err_sys("signal error");

        printf("%% ");  /* print prompt (printf requires %% to print %) */
        while (fgets(buf, MAXLINE, stdin) != NULL) {
                if (buf[strlen(buf) - 1] == '\n')
                        buf[strlen(buf) - 1] = 0; /* replace newline with null */

                if ((pid = fork()) < 0) {
                        err_sys("fork error");
                } else if (pid == 0) {      /* child */
                        execlp(buf, buf, (char *)0);
                        err_ret("couldn't execute: %s", buf);
                        exit(127);
                }

                /* parent */
                if ((pid = waitpid(pid, &status, 0)) < 0)
                        err_sys("waitpid error");
                printf("%% ");
        }
        exit(0);
}

void
sig_int(int signo)
{
        printf("interrupt\n%% ");
}

Three problems:

  1. “Slow” system calls may get interrupted on signals
  2. Signals get lost
  3. Signal handler calls non-reentrant functions

Solutions:

File sharing

  1. Kernel data structures for open files

    Figure 3.7, APUE
    Figure 3.7, APUE
  2. Two independent processes with the same file open

    Figure 3.8, APUE
    Figure 3.8, APUE
  3. Kernel data structures after dup(1)

    Figure 3.9, APUE
    Figure 3.9, APUE
  4. Sharing of open files between parent and child after fork

    Figure 8.2, APUE
    Figure 8.2, APUE

Last updated: 2014–02–03