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>
#include <unistd.h>
#include <stdlib.h>
typedef struct parameter
{
int count;
}param;
int main()
{
FILE *fp;
int i;
param p;
fp = fopen("data.txt","w+");
if(fp == NULL)
{
printf("\nCannot open file.");
exit(1);
}
i = 0;
while(1)
{
p.count = i++;
printf("\nWriting count = %d",p.count);
fwrite(&p,sizeof(p),1,fp);
sleep(5);
}
fclose(fp);
return(0);
}
//Reader
Code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
typedef struct parameter
{
int count;
}param;
int main()
{
FILE *fp;
int x;
param p;
fp = fopen("data.txt","r");
if(fp == NULL)
{
printf("\nCannot open file.");
exit(1);
}
while(1)
{
x = fread(&p,sizeof(p),1,fp );
printf("\nReading:count =%d",p.count);
sleep(1);
}
printf("\nOut of while...");
fclose(fp);
return(0);
}
I have searched about it and stumbled across file-locking, but don't know how to code it. Then I came across one process writing and renaming the file etc. Any help will be appreciated. Thanks.
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.