LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   lock file between two process (https://www.linuxquestions.org/questions/programming-9/lock-file-between-two-process-573027/)

shogun1234 07-28-2007 03:45 PM

lock file between two process
 
I need to lock a file, which will be accessed by a Java program (multi-thread). The content of the file is written by a C programme. I try the file lock (similar to the book - Advanced Linux Programming). It doesn't work because when reading the file and paring it, it returned with a error, saying no content inside the file (but `cat file_name` I can see the content exactly there). How can I lock a file that can prevent other processes (the Java programme) access the file before the writing process (the C programme) finishes its jobs? Or what to do to prevent such problem occurs?

The code snippet of locking file in C I write is as follow:
Code:

...
        memset(&lock, 0, sizeof(lock));
        lock.l_type = F_WRLCK;
        fcntl(fd, F_SETLK, &lock);

        //prepare content
...
        /* unlocking file */
        lock.l_type = F_UNLCK;
        fcntl(fd, F_SETLK, &lock);
...

Thanks in advice,

wjevans_7d1@yahoo.co 07-28-2007 04:29 PM

Most file locking is "advisory locking", in which processes must cooperate with each other in order for the locking to take effect. If you're trying to lock out from a file any arbitrary unknown code, advisory locking won't work.

No, you want "mandatory locking". See:

http://linux-security.cn/ebooks/ulk3...12-SECT-7.html

For words from the Linux horse's mouth, see:

http://www.in-ulm.de/~mascheck/vario.../mandatory.txt

Hope this helps.

binutils 07-28-2007 10:54 PM

man select


All times are GMT -5. The time now is 06:00 PM.