怪异的行为时prepending与猫和三通的文件 [英] Weird behavior when prepending to a file with cat and tee

查看:141
本文介绍了怪异的行为时prepending与猫和三通的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个解决问题的办法从 prePEND到一个文件一行外壳是:

One solution to the problem from prepend to a file one liner shell? is:

cat header main | tee main > /dev/null

正如一些评论注意到,这并不对大的文件。

As some of the comments noticed, this doesn't work for large files.

下面就是它的工作原理的例子:

Here's an example where it works:

$ echo '1' > h
$ echo '2' > t
$ cat h t | tee t > /dev/null
$ cat t
1
2

和它打破了:

$ head -1000 /dev/urandom > h
$ head -1000 /dev/urandom > t
$ cat h t | tee t > /dev/null
^C

该命令挂起,杀死后留给我们的是:

The command hangs and after killing it we are left with:

$ wc -l t
7470174 t

是什么原因导致上述行为所在的命令卡和无限增加线?什么是在1号线不同的文件的情况?

What causes the above behavior where the command gets stuck and adds lines infinitely? What is different in the 1 line files scenario?

推荐答案

的行为是完全不确定性。当你做猫头主要|开球主>的/ dev / null的,下面的事情发生了:

The behavior is completely non-deterministic. When you do cat header main | tee main > /dev/null, the following things happen:

1)打开猫头
2)打开猫主
3)猫读取头和它的内容写到stdout
4)猫主读取其内容写到stdout
5)打开三通主要用于写作,截断它
6)三通标准输入读取和写入读取到主数据

1) cat opens header 2) cat opens main 3) cat reads header and writes its content to stdout 4) cat reads main and writes its content to stdout 5) tee opens main for writing, truncating it 6) tee reads stdin and writes the data read into main

上面的顺序是一种可能的顺序,但在许多不同的顺序,可能会发生这些事件。 5必须precede 6,2绝precede 4,和1绝precede 3,但它是完全有可能的排序为5,1,3,2,4,6。在任何情况下,如果文件是大的,这是非常可能的是前步4是完整的,这将导致数据的部分将被丢弃步骤5将发生。这是完全可能的,步骤5先发生,在这种情况下,所有的数据$ P $的pviously在主将丢失。

The ordering above is one possible ordering, but these events may occur in many different orders. 5 must precede 6, 2 must precede 4, and 1 must precede 3, but it is entirely possible for the ordering to be 5,1,3,2,4,6. In any case, if the files are large, it is very likely that step 5 will take place before step 4 is complete, which will cause portions of data to be discarded. It is entirely possible that step 5 happens first, in which case all of the data previously in main will be lost.

这是你所看到的特定情况下,很可能猫阻塞写和去之前,它已完成读取输入睡觉的结果。 T恤然后写入更多的数据 T ,并尝试从管道读取,然后进入休眠状态,直到猫写入更多的数据。 写缓冲, T恤将其放入 T ,并且循环重复。

The particular case that you are seeing is very likely a result of cat blocking on a write and going to sleep before it has finished reading the input. tee then writes more data t and tries to read from the pipe, then goes to sleep until cat writes more data. cat writes a buffer, tee puts it into t, and the cycle repeats.

这篇关于怪异的行为时prepending与猫和三通的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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