我在 bash 中遇到了竞争条件吗?

Nat*_*han 3 shell bash pipe concurrency process-substitution

我有一个脚本,它将命令的输出与之前运行的相同命令的输出进行比较,它在大多数情况下都可以工作,但时不时地无法按预期工作。

我已经能够在一个测试线上重现这个问题。我知道我可以轻松地将其分解为比较两个单独的文件,问题就会消失,但我想了解这里实际发生了什么,以及是否有办法以我的方式实现我想要实现的目标我正在努力实现它。

下面是我多次运行的命令的输出,您可以看到它在其中一种情况下回显“test”,但大多数时候它按预期工作。

root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
test
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
root@dev:~# comm -13 /tmp/test <(echo '"test"' | cut -d'"' -f2 | sort -u | tee /tmp/test)
Run Code Online (Sandbox Code Playgroud)

我正在跑步Ubuntu 10.04bash 4.1-2ubuntu3.5并且coreutils 7.4-2ubuntu3

Luc*_*cas 5

是的,这是一个竞争条件。

问题是 shell 同时启动管道中的所有进程,并且 tee 在启动时截断输出文件。如果 tee 更快,则 comm 文件为空,否则为空。

如果您多次运行(可能在循环中),则可以看到管道行为:

date '+first:  %T'|(cat>&2;sleep 5)|date '+second: %T'
Run Code Online (Sandbox Code Playgroud)