I need to write c code on linux that will check if
1) a file exists and
2) if it does not exist then I need to open the file and write into the file.
Being a multi thread / multi process environment, I want to ensure that 1 and two above happen in one atomic operation
I looked at What's the best way to check if a file exists in C? (cross platform) and considered solution suggested by @Dan Lenski. So please dont mark this as duplicate without reading completely . The problem with that is the combination of O_CREAT | O_WRONLY | O_EXCL flags in an open system call as mentioned in open man page does not tolerate symbolic links. Sounds like it has problems with NFS partitions as well
We do use symbolic links in our paths ( Debatable - why but we do end up using ) so I want to do something akin Dan's suggested and cited in his code fragment reproduced below but what can tolerate a path that points to a symbolic link
#include <fcntl.h>
#include <errno.h>
fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* failure */
if (errno == EEXIST) {
/* the file already existed */
...
}
} else {
/* now you can use the file */
}