深入理解计算机系统-第十章 系统级I/O-相关函数

链接
系统级I/O
相关函数
结果分析

ffiles1.c

#include "csapp.h"
int main(int argc, char *argv[])
{
    int fd1, fd2, fd3;
    char c1, c2, c3;
    char *fname = argv[1];
    fd1 = Open(fname, O_RDONLY, 0);
    fd2 = Open(fname, O_RDONLY, 0);
    fd3 = Open(fname, O_RDONLY, 0);
    dup2(fd2, fd3);
    Read(fd1, &c1, 1);
    Read(fd2, &c2, 1);
    Read(fd3, &c3, 1);
    printf("c1 = %c, c2 = %c, c3 = %c\n", c1, c2, c3);
    Close(fd1);
    Close(fd2);
    Close(fd3);
    return 0;
}

ffiles2.c

#include "csapp.h"
int main(int argc, char *argv[])
{
    int fd1;
    int s = getpid() & 0x1;
    char c1, c2;
    char *fname = argv[1];
    fd1 = Open(fname, O_RDONLY, 0);
    Read(fd1, &c1, 1);
    if (fork()) {
    /* Parent */
    sleep(s);
    Read(fd1, &c2, 1);
    printf("Parent: c1 = %c, c2 = %c\n", c1, c2);
    } else {
    /* Child */
    sleep(1-s);
    Read(fd1, &c2, 1);
    printf("Child: c1 = %c, c2 = %c\n", c1, c2);
    }
    return 0;
}

ffiles3.c

#include "csapp.h"
int main(int argc, char *argv[])
{
    int fd1, fd2, fd3;
    char *fname = argv[1];
    fd1 = Open(fname, O_CREAT|O_TRUNC|O_RDWR, S_IRUSR|S_IWUSR);
    Write(fd1, "pqrs", 4); 
    fd3 = Open(fname, O_APPEND|O_WRONLY, 0);
    Write(fd3, "jklmn", 5);
    fd2 = dup(fd1);  /* Allocates new descriptor */
    Write(fd2, "wxyz", 4);
    Write(fd3, "ef", 2);
    Close(fd1);
    Close(fd2);
    Close(fd3);
    return 0;
}

statcheck.c

#include "csapp.h"
int main (int argc, char **argv) 
{
    struct stat stat;
    char *type, *readok;
    /* $end statcheck */
    if (argc != 2) {
 	fprintf(stderr, "usage: %s \n", argv[0]);
    exit(0);
    }
    /* $begin statcheck */
    Stat(argv[1], &stat);
    if (S_ISREG(stat.st_mode))     /* Determine file type */
	 type = "regular";
    else if (S_ISDIR(stat.st_mode))
	 type = "directory";
    else 
	 type = "other";
    if ((stat.st_mode & S_IRUSR)) /* Check read access */
	 readok = "yes";
    else
	 readok = "no";
    printf("type: %s, read: %s\n", type, readok);
    exit(0);
}

你可能感兴趣的:(深入理解计算机系统-第十章 系统级I/O-相关函数)