Operating System - Linux
1828219 Members
1920 Online
109975 Solutions
New Discussion

2 program writing to same file

 
Henry Chua
Super Advisor

2 program writing to same file

Hi Guys,

I have 2 programs written in C in my process that needs to write to a log file, can I know how I can facilitate these programs so that no contention occurs?

Best regards
Henry
6 REPLIES 6
Vibhor Kumar Agarwal
Esteemed Contributor

Re: 2 program writing to same file

This is one of the basic problems.

Gather some information about Semaphores.
Vibhor Kumar Agarwal
Rajeev  Shukla
Honored Contributor

Re: 2 program writing to same file

One option is you create a LOCK file.
When ever a program writes to the log file it creates a LOCK file and so that the other program waits till it sees the LOCK file is no more there and then writes back and once done it removes the LOCK file.

Cheers
Rajeev
Bejoy C Alias
Respected Contributor

Re: 2 program writing to same file

Check fcntl()
Be Always Joy ......
Ralph Grothe
Honored Contributor

Re: 2 program writing to same file

Your IPC programs must device some sort of locking to avoid race conditions.
Advisory locking is quite often done through the fcntl() syscall (see manpage),
or the flock() function in Perl.
As the term advisory implies this only works if your processes obey the locks at all.
Madness, thy name is system administration
Muthukumar_5
Honored Contributor

Re: 2 program writing to same file

You have to use file locking with fcntl() call. It will control this problem. When one process is trying then next process will check what is the status of log file (is it writable or not). If get the access starts to access it.

hth.
Easy to suggest when don't know about the problem!
Daavid Turnbull
Frequent Advisor

Re: 2 program writing to same file

fcntl() is obviously a better option but the simple aproach of using a lock file is better implimented by creating a directory instead of a file as the create and test for existance can be implimented as a single call and more efficient that using something like open() with the appropriate options.
Behold the turtle for he makes not progress unless he pokes his head out.