Two users writing to same file in C?

Wim

Registered
I understand I may create a file full of garbage when I let two users write into the same file at the same time using C's fprintf.
I need a solution to this for a multi-user application that is supposed to write log into a single log file.
Is there a standard strategy to solve this in C? (I suppose this a 'natural' for a production environment)

Any suggestion or link is very welcome.

Regards,
Wim
(rather new to C)
 
You need to implement file locking. In case the files reside in the local file system, use flock(2). However, if you want the locking to work with NFS-mounted file systems as well you have to use fcntl(2).

The following sample provides file locking and unlocking. On locking it also deals with the EINTR error which can happen if the fcntl blocks due to a locking conflict but is interrupted by a signal.

These functions assume that you have an int fd filedescriptor referring to the file in question. They return zero on success.

The lock_file function blocks on any locking conflict (i.e. waits until the file is unlocked by someone else).

<code>

#include &lt;unistd.h&gt;
#include &lt;fcntl.h&gt;

int lock_file(int fd)
{
&nbsp;&nbsp;&nbsp;struct flock flk;

&nbsp;&nbsp;&nbsp;flk.l_type = F_WRLCK;
&nbsp;&nbsp;&nbsp;flk.l_whence = 0;
&nbsp;&nbsp;&nbsp;flk.l_start = 0;
&nbsp;&nbsp;&nbsp;flk.l_len = 0;

&nbsp;&nbsp;&nbsp;while (fcntl(fd, F_SETLKW, &flk) < 0)
&nbsp;&nbsp;&nbsp;{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (errno != EINTR)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return -1;
&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;return 0;
}

int unlock_file(int fd)
{
&nbsp;&nbsp;&nbsp;struct flock flk;

&nbsp;&nbsp;&nbsp;flk.l_type = F_UNLCK;
&nbsp;&nbsp;&nbsp;flk.l_whence = 0;
&nbsp;&nbsp;&nbsp;flk.l_start = 0;
&nbsp;&nbsp;&nbsp;flk.l_len = 0;

&nbsp;&nbsp;&nbsp;return fcntl(fd, F_SETLK, &flk);
}

</code>

Hope this helps.
 
If you have a FILE* fp instead of an int fd you can simply do the following:

int fd = fileno(fp);
 
There is some overhead with locking and unlocking the file and you have to be very careful about all the nastiness with deadlocks and starvation. Not that there are not times when this would be appropriate.

Depending one what you are logging another simple solution is just to use the built in syslog functionality. That way you can leverage the existing infrastructure. If you still want to go your own way a similar approach with a single logger process which actually writes to the file while then talks to the various client processes via a set of pipes or via the net may still be a better approach.

-Eric
 
Back
Top