什么>> 2&所述;&放大器1 QUOT;在Bourne shell的重定向呢? [英] What does "2<&1" redirect do in Bourne shell?

查看:132
本文介绍了什么>> 2&所述;&放大器1 QUOT;在Bourne shell的重定向呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

2 - ;&放大器; 1 重定向Bourne shell中需要发送到文件描述符2(默认情况下,标准错误)的输出,并发送它,而不是文件描述符1(默认情况下,标准输出)。

2>&1 redirect in Bourne shell takes the output sent to a file descriptor 2 (by default, standard error) and sends it instead to file descriptor 1 (by default a standard output).

但什么是 2';&放大器; 1 重定向做

是否发送错误输出到标准输入?

Does it send stderr to stdin?

我的理论是,它发送标准输入到标准错误(例如相同 1>和2 ),但实验,这是不是这样的:

My theory was that it was sending stdin to stderr (e.g. same as 1>&2) but experimentally, that is NOT the case:

$ perl -e 'print "OUT\n"; print STDERR "ERR\n"; \
  while (<>) { print "IN WAS $_\n";}'           \
  > out3 2<&1
df
$ cat out3
ERR
OUT
IN WAS df

请注意,标准输出和标准错误都上了文件OUT3的地方标准输出被重定向。

Note that standard out AND standard error both went to file out3 where stdout was redirected.

推荐答案

&LT;&安培; 运营商复制输入文件描述符。根据IEEE标准1003.1-2001(又名单一Unix规格V3的继任者POSIX),它应该是一个错误的说 2';&放大器; 1 如果1没有一个文件描述符打开输入。然而,似乎庆典是懒惰和不关心,如果文件描述符是开放的输入或输出。

The <& operator duplicates an "input" file descriptor. According to IEEE Std 1003.1-2001 (aka Single Unix Specification v3, the successor to POSIX), it's supposed to be an error to say 2<&1 if 1 is not a file descriptor open for input. However, it appears that bash is lazy and doesn't care if the file descriptor is open for input or for output.

因此​​,无论 2';&放大器; 1 2 - ;&放大器; 1 只需执行系统调用 dup2(1,2),它复制文件描述符1文件描述符2。

So both 2<&1 and 2>&1 simply perform the system call dup2(1, 2), which copies file descriptor 1 to file descriptor 2.

您可以通过运行这样的命令检查,因为重定向执行左到右:

You can check by running a command like this, since redirections are performed left-to-right:

sleep 99999 1>/dev/null 2<&1

然后在另一个窗口中,睡眠过程中运行 lsof的。你会看到两个文件描述符1和2点的/ dev / null的。例如(在我的Mac):

Then in another window, run lsof on the sleep process. You'll see that both file descriptors 1 and 2 point to /dev/null. Example (on my Mac):

:; ps axww | grep sleep
 8871 s001  R+     0:00.01 grep sleep
 8869 s003  S+     0:00.01 sleep 99999
:; lsof -p 8869 | tail -2
sleep   8869 mayoff    1w   CHR    3,2       0t0       316 /dev/null
sleep   8869 mayoff    2w   CHR    3,2       0t0       316 /dev/null

这篇关于什么>> 2&所述;&放大器1 QUOT;在Bourne shell的重定向呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆