Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

race condition betwen script and C binary program

Tags:

c

linux

bash

shell

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?

like image 281
MOHAMED Avatar asked Feb 11 '23 19:02

MOHAMED


1 Answers

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).
like image 112
jm666 Avatar answered Feb 13 '23 21:02

jm666