1

I have a C program and a bash script that need exclusive access to a file. I've seen that you can use mkdir with bash, but does this mix well with C? Is it safe to just test the presence of a directory, create and then delete it?

What I'm actually doing: a C program keeps rewriting a file with new data that is then read from a bash script.

5
  • What's your problem? I'm not sure what you're really asking here. Commented Oct 13, 2016 at 8:07
  • 2
    Write to a differently named file in C and when you are finished writing it, rename it such that it overwrites the existing file. If the bash script happens to be reading the file as you overwrite it, it will still be able to finish reading the file if it has it open. Then next time the bash script opens the file, it will get the newly renamed one. Commented Oct 13, 2016 at 8:17
  • While I have accepted @Dmitry answer as it addresses my question, I'm going with your suggestion as it effectively solves my problem in a simpler way and without semaphores to begin with. Commented Oct 13, 2016 at 8:28
  • The suggestion is indeed nice, but keep in mind that if your C code runs quickly enough to create two new files or more while the shell script reads one, the script will miss some of the files. Commented Oct 13, 2016 at 8:30
  • If the writing is frequent, the idea of the file being on a small RAMdisk comes to mind - to save thrashing your disk... stackoverflow.com/a/39924756/2836621 Commented Oct 14, 2016 at 0:22

1 Answer 1

3

The whole point of semaphores is atomicity, and if you check for directory presence using your own code, you will lose that property. What you should do it use mkdir function and check for EEXIST error code once it returns:

char * lockdir="/tmp/myscript.lock";
int retval=mkdir(lockdir, S_IRWXU);
if(retval == 0) printf("successfully acquired lock: %s", lockdir);
else if(errno == EEXIST) printf("cannot acquire lock %s", lockdir);
else printf("Something bad happened (permissions/no free space/read-only filesystem)")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.