无法创建常规文件“文件名”:文件存在


23

我一直在我的一个构建脚本中收到此奇怪的错误消息- cp失败,返回错误“文件存在”。我什至尝试使用cp -f,如果文件存在,它将覆盖该文件,但错误仍然出现。运行cp覆盖现有文件,当我做手工完美。是什么导致此错误?

Answers:


25

事实证明这是由于比赛条件引起的。cp检查目标文件是否已经存在,如果不存在,则将其覆盖。发生问题是因为该cp命令并行运行两次,这导致有问题的文件有时在检查文件是否存在之后但在尝试创建文件之前出现。该strace输出如下所示:

# Command was "cp a b"
stat("b", 0x7fff89510620)               = -1 ENOENT (No such file or directory)
stat("a", {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
stat("b", 0x7fff895103a0)               = -1 ENOENT (No such file or directory)
# File b will be created at this point in time
open("a", O_RDONLY)                     = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
open("b", O_WRONLY|O_CREAT|O_EXCL, 0644) = -1 EEXIST (File exists)

以下是一些用于捕获此内容的bash代码:

#!/bin/bash

touch a

f() {
  while true; do
    rm -f b
    strace -o /tmp/cp${BASHPID}.trace cp a b || break
  done
}

cleanup() {
  kill -9 %1 %2
}

f &
f &

trap cleanup exit

wait

mkdir -p尝试覆盖文件或执行任何其他尝试覆盖文件的操作时,可能会发生相同的错误。flock在这种情况下,使用可以帮助避免出现竞争状况。


我遇到了完全相同的情况。我选择通过||操作员来处理。有点像穷人的尝试/抓住。即,cp ... || echo "skip copying due to other thread"。或类似的东西
— icfantv

我在运行单曲时遇到了这个问题cp
— 赵刚

遇到同样的问题。您是如何调试的?
— CIsForCookies

失败了cp。
— lutzky
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.