Writing to and reading from a common file simultaneously via two different processes
Dear All,
There are two processes. Process 1 writes to a file. Process 2 reads from the same file. This is simultaneous. But, the first process locks the file. So I am unable to do it. Here is my code. // Writer Code:
#include <stdio.h> Code:
#include <stdio.h> PS: I want two processes to communicate via a common file. I know it can be done via sockets, but this time I want to do it via common file because I want to learn how to do it this way properly. |
In the Writer application, after you perform the fwrite(), perform an fflush(). See if that makes a difference.
|
Thanks dwhitney67 for the reply.
Yes, it works after fflush(fp). // I searched and learned that fflush flushes out the buffer associated with a stream. Thanks. The writer process opens a file and then enters an infinite loop. So the other process should not be allowed to open the file and get a file handle (?). But I guess that it was allowed in this case. Could you please explain it? Also, please tell me if there is a better way to do this via common file? Thanks in advance. |
Is there a reason you aren't using a named pipe? A named pipe will allow the reader to block for more data (instead of requiring a spinlock), with the drawback being that only one process can read from it. If you stick with the regular file, you should use advisory locks (see fcntl F_GETLK, etc.), anyway; otherwise, you might get partial-line reads from the reader while the writer is writing. Lastly, consider using "a+" instead of "w+".
Kevin Barry |
All times are GMT -5. The time now is 02:52 AM. |