1

I have a part of a bash script, which I am executing as root:

rm -f ../../include/profile.h; \
cp profile.h ../../include/profile.h

the file ../../include/profile.h in question has permissions:

-rw-r--r-- 1 root root 12178 Nov  5 02:00 ../../include/profile.h

Most of the time, the snippet executes fine, but very rarely, impossible to reproduce, it fails:

cp: cannot create regular file `../../include/profile.h': File exists

I checked, there is no other part of the program, that would be executed in parallel, which could write the file in between the two statements, thus creating a race condition which would explain the behaviour. There is no other place than the above, which is executed only once, which would write this file.

The system is

kernel:

Linux dev64 2.6.32.63+drm33.26-64.128-a10 #6 SMP Fri Jul 25 15:21:56 PDT 2014 x86_64 x86_64 x86_64 GNU/Linux

distro:

CentOS release 6.3 (Final)

What could possibly cause this failure to appear??

Giacomo1968
  • 58,727

2 Answers2

0

Use

strace cp profile.h ../../include/profile.h 2>logfile

and look for:

stat("../../include/profile.h", 0x7ffdca347950) = -1 ENOENT (No such file or directory)
open("../../include/profile.h", O_WRONLY|O_CREAT|O_EXCL, 0600) = 4

That will tell you what's going on. In this example the file did not exist before the cp (which it determined), hence the O_CREAT|O_EXCL.

ctrl-d
  • 136
-2

It may be a race condition when different processes are writing to a same file location.

cp process A:

  • action1: found the file not exist
  • action2: create the file

cp process B:

  • action1: found the file not exist
  • action2: create the file

When B.action2 happen between A.action1 and A.action2, A will report "cp: cannot create regular file '???': File exists"