zoukankan      html  css  js  c++  java
  • 深入理解计算机系统_3e 第十章家庭作业 CS:APP3e chapter 10 homework

    **10.6**

    1.若成功打开“foo.txt”:

    -->1.1若成功打开“baz.txt”: 输出“4 ”

    -->1.2若未能成功打开“baz.txt”: 输出“-1 ”

    2.若未能成功打开“foo.txt”:

    -->2.1若成功打开“baz.txt”: 输出“3 ”

    -->2.2若未能成功打开“baz.txt”: 输出“-1 ”


    10.7

    #include "csapp.h"
    
    int main(int argc, char **argv) 
    {
        int n;
        rio_t rio;
        char buf[MAXBUF];
    
        Rio_readinitb(&rio, STDIN_FILENO);
        while((n = Rio_readnb(&rio, buf, MAXBUF)) != 0) 
    	    Rio_writen(STDOUT_FILENO, buf, n);
        exit(0);
    }
    

    10.8

    #include "csapp.h"
    #include "csapp.c"
    #include <string.h>
    #include <stdio.h>
    
    int main (int argc, char **argv) 
    {
        struct stat stat;
        char *type, *readok;
        char buf[MAXBUF];
        char filename[MAXBUF];
        memset(buf, 0, MAXBUF);
        memset(filename, 0, MAXBUF);
    
        if (argc != 2)  {
        fprintf(stderr, "usage: %s <descriptor number>
    ", argv[0]);
        exit(0);
        }
             
        sprintf(buf+sprintf(buf, "/proc/self/fd/"), argv[1]);
    
        if(readlink(buf, filename, sizeof(filename)) == -1)
        {
            fprintf(stderr, "bad file descriptor
    ");
            exit(EXIT_FAILURE);
        }
    
        Stat(filename, &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
    ", type, readok);
        exit(0);
    }
    

    参考:Getting Filename from file descriptor in C


    10.9

    这里只是模拟一下基本的操作,就是将文价描述符argv[1](3)指向“foo.txt”(STDIN_FILENO),shell实际实现肯定有许多没写到的。

    if (Fork() == 0){ /* child */
      dup2(STDIN_FILENO, atoi(argv[1]));
      Execve("fstatcheck", argv, envp);
    }
    

    10.10

    如果有infile参数的话,将STDIN_FILENO指向该文件。

    #include "csapp.h"
    
    int main(int argc, char **argv) 
    {
        int n;
        rio_t rio;
        char buf[MAXLINE];
    
        if (argc == 2) /* infile */
        {
            int fd = open(argv[1], O_RDONLY|O_CREAT);
            dup2(fd, STDIN_FILENO);
            close(fd);
        }
    
        Rio_readinitb(&rio, STDIN_FILENO);
        while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0) 
    	    Rio_writen(STDOUT_FILENO, buf, n);
    
        exit(0);
    }
    

  • 相关阅读:
    yii主题
    aptana studio 使用技巧整理
    big database url
    yii表单输入元素
    下载,和scp上传问题
    对缓存的思考——提高命中率
    php用户名密码
    openx -书表添加字段
    搜索
    python——常用模块2
  • 原文地址:https://www.cnblogs.com/liqiuhao/p/8305036.html
Copyright © 2011-2022 走看看