I have a test of C++ code that in most runs passes, but in some rare instances fails due to the call to lchown() in my application under test, failing with errno EPERM and strerror:
Operation not permitted.
The code in question in my application is like this:
::lchown("pathnameToFile", uid_t(500), static_cast<unsigned>(-1)); // This line works
::lchown("pathnameToFile", static_cast<unsigned>(-1), gid_t(500)); // This fails rarely
Also in the test case iteration that failed, the prior attempt to create a symbolic link to the "pathnameToFile" also failed to create it in my application, but the code did not detect any error (the following returned 0):
::symlink("pathnameToFile", "linkToPathname");
I imagine these two things are related. This is running on a 32 bit Centos 4 machine.
The "pathnameToFile" exists on an NFS mounted partition. Could there be some kind of race condition between the file being created and the link to it and lchown failing because the NFS does not reflect its existence yet?
After some time elapsed however, the symbolic link appeared although the chown remained without effect.
The "pathnameToFile" lives in a directory with permissions:
drwxrwxr-x 2 me me 4096 Jun 22 17:33 .
-rw-rw-r-- 1 me root 33 Jun 22 17:33 pathnameToFile
lrwxrwxrwx 1 me root 8 Jun 22 17:33 LinkToPathname -> pathnameToFile
The gid 500 is the primary group for 'me', the other group being 'wheel'.
> groups
me wheel
It is a race condition, add a short sleep when the lchown fails and try again.