简体   繁体   中英

race condition betwen script and C binary program

I have a program in C that is writing data to a file.

The C program does not keep the file opened during the execution, It just open the file with ( fopen ("myfile.txt","a") ) and write some data and then close the file.

In other side I have a script file that could make 2 actions on the same file at the same time with The C binary program:

  1. It could remove the file

  2. it could add some lines to the file with the command

     echo "some data" >> file 

Are there a risk of race condition betwen script and C binary program? Does the Linux ioctl could manage a such issue?

If there is a risk of race condition, how to make a check on C and shell before treating the file?

If two processes writing into the same file without any "treatment", always exists an race condition. (maybe statistically small - but still exists).

You can:

  • lock the file using the OS calls, like fcntl , flock (see for example this qst )
  • create an external "lock-file" such /some/path/file.lck (the content is usually the hostname and process ID (pid) of the locking process - what allow detect stalling locks) and check its existence (and/or content) before every modification of the original file. After the modification, you can simply remove the "lock-file"). It is much slower as OS-level locking, but it is easy to handle and very handy for "locking" in the shell-scripts). (Remember, file-creation is always atomic).

You need to create some kind of semaphore between your C program and your shell.

One of the easiest ways to do this is to set the sticky bit on the file. Make your program set this value and unset it, and have the bash script check whether it's set. If it does, you can just make the script hang until it's unset.

To add the bit, you would use posix chmod and add 1000 octal to the file's permissions (and subtract 01000 when you want to remove it). To test it in the bash file, among other things, you can use find, eg for a file named foo.txt, you could do find . -name foo.txt -perm 1000 find . -name foo.txt -perm 1000 and see if the find returns a value. (I got that snippet idea off of a question on unix.com ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM