• 深入理解计算机系统_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);
    }
    

  • 相关阅读:
    博弈最高位POJ 1704(Georgia and BobNim博弈)
    图片优化ios学习之真机测试 copy图片错误解决方案
    输入左移校草计划(Nim)
    类型函数C语言void关键字
    图层设置GDAL/OGR创建DXF文件中多图层的方法
    浏览器下载Firefox os 模拟器安装教程步骤详解
    工程图标ios学习之给程序设置logo
    实例收藏Android开发环境搭建和Android开发基础知识汇总值得收藏
    乱码插入mac mysql汉字乱码问题解决
    菜菜从零学习WCF一(WCF概述)
  • 原文地址:https://www.cnblogs.com/liqiuhao/p/8305036.html
Copyright © 2020-2023  润新知