**10.6**
1.若成功打开“foo.txt”:
-->1.1若成功打开“baz.txt”: 输出“4\n”
-->1.2若未能成功打开“baz.txt”: 输出“-1\n”
2.若未能成功打开“foo.txt”:
-->2.1若成功打开“baz.txt”: 输出“3\n”
-->2.2若未能成功打开“baz.txt”: 输出“-1\n”
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>\n", 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\n");
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\n", 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);
}