Linux 当我们使用“重定向”时,shell会做什么<&引用;?

Linux 当我们使用“重定向”时,shell会做什么<&引用;?,linux,shell,process,Linux,Shell,Process,假设我有一个名为fstatcheck的程序。它从命令行获取一个参数,并将其视为文件描述符。它检查由文件描述符指向的文件的stat信息 例如: $./fstatcheck 1 l = 1 type: other, read: yes $./fstatcheck 3 < foobar.txt l = 3 Fstat error: Bad file descriptor 另一个例子: $./fstatcheck 1 l = 1 type: other, read: yes $./fsta

假设我有一个名为fstatcheck的程序。它从命令行获取一个参数,并将其视为文件描述符。它检查由文件描述符指向的文件的stat信息

例如:

$./fstatcheck 1
l = 1
type: other, read: yes
$./fstatcheck 3 < foobar.txt 
l = 3
Fstat error: Bad file descriptor
另一个例子:

$./fstatcheck 1
l = 1
type: other, read: yes
$./fstatcheck 3 < foobar.txt 
l = 3
Fstat error: Bad file descriptor
  • 是否有任何方法可以创建一个文件描述符3,并让它通过使用shell命令(而不是使用C代码)连接到指向foobar.txt file stat的打开文件表


  • 让我们通过
    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
    [...]
    
    至于打开另一个fd,绝对:

    myprogram 3< file
    
    myprogram 3

    这将打开
    文件
    ,以便在fd 3上读取程序<代码>让我们用
    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
    [...]
    
    至于打开另一个fd,绝对:

    myprogram 3< file
    
    myprogram 3

    这将打开
    文件
    ,以便在fd 3上读取程序<代码>堆栈溢出是一个关于编程和开发问题的网站。这个问题似乎离题了,因为它与编程或开发无关。请参见帮助中心中的。也许或者会是一个更好的提问的地方。另请参见Stack Overflow是一个关于编程和开发问题的网站。这个问题似乎离题了,因为它与编程或开发无关。请参见帮助中心中的。也许或者会是一个更好的提问的地方。也看到