2017-06-04 44 views
0

假设我有一个名为fstatcheck的程序。它从命令行获取一个参数并将其视为文件描述符。它检查文件描述符指向的文件的统计信息。当我们使用“<”重定向时,shell会做什么?

例如:

$./fstatcheck 1 
l = 1 
type: other, read: yes 

又如:

$./fstatcheck 3 < foobar.txt 
l = 3 
Fstat error: Bad file descriptor 

问题:

  1. 是什么shell在第二个例子中做什么? 我可以猜测,它需要3作为文件描述符,并开始分析统计,但描述符3未打开。但是shell如何处理重定向呢?

    我承担壳执行下面的算法:

    if (fork() == 0) { 
        // What does the shell do here? 
        execve("fstatcheck", argv, envp); 
    } 
    
  2. 有什么办法,我可以创造一个文件描述符3,让它连接到哪个点通过向foobar.txt文件统计的打开文件表只使用shell命令(而不是使用C代码)?

+0

Stack Overflow是编程和开发问题的网站。这个问题似乎与题目无关,因为它不涉及编程或开发。请参阅帮助中心的[我可以询问哪些主题](http://stackoverflow.com/help/on-topic)。也许[超级用户](http://superuser.com/)或[Unix&Linux堆栈交换](http://unix.stackexchange.com/)会是一个更好的地方。另请参阅[我在哪里发布有关Dev Ops的问题?](http://meta.stackexchange.com/q/134306) – jww

回答

4

让我们来看看有strace

$ strace sh -c 'cat < /dev/null' 
[...] 
open("/dev/null", O_RDONLY)    = 3 
fcntl(0, F_DUPFD, 10)     = 10 
close(0)        = 0 
fcntl(10, F_SETFD, FD_CLOEXEC)   = 0 
dup2(3, 0)        = 0 
close(3)        = 0 
[...] 
execve("/bin/cat", ["cat"], [/* 28 vars */]) = 0 
[...] 
在你的代码

因此,相关部分将是:

if (fork() == 0) { 
    int fd = open(filename, O_RDONLY); // Open the file 
    close(0);       // Close old stdin 
    dup2(fd, 0);      // Copy fd as new stdin 
    close(fd);       // Close the original fd 
    execve("fstatcheck", argv, envp); // Execute 
} 

至于打开另一个FD,绝对:

myprogram 3< file 

这会打开用于在节目3上读取fd 3的n file。单独是<0<的同义词。

相关问题