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);
    }
    

  • 相关阅读:
    opencv源码编译安装后使用时出现undefined reference cv::imwrite
    OPPO手机永久打开USB调试模式
    bash 顺序执行等待前一个脚本执行完成
    cpp
    多线程
    关于nvme下ubuntu无法识别硬盘的问题
    极限建站
    新生赛
    pc_mbed_fpga_communication
    color_sensor_mbed
  • 原文地址:https://www.cnblogs.com/liqiuhao/p/8305036.html
Copyright © 2011-2022 走看看