I have a project in which several writers(using multi thread) write using one process and single reader(Single thread) reads this write through another process. Writer and reader keep doing the same. Writer writes variable lines of data in every write so i cannot use buffer. I think to use either memory map files or single file in which i can write this.
I am confused for synchronization. As am doing this in 2 process so cannot use condition variables so need to use semaphore only.
Now if i use semaphore then several writer write at same time so its overwrite previous data write by another writer and when reader reads it will read only latest write and i will lost all previous write.I want reader should read every write happened. Some delay is acceptable.
I can also try one thing write all in a file then sleep threads for some time and read them during that sleep but by doing this i may lost some data which may arrived during sleep time.
Any idea how to implement the same? Any help is great. I am using C and Linux platform. So kindly suggest related to C and Linux/Unix.
Update1: I have done following steps for semaphore:
semget(key,2,flag) //define 2 semaphore
semctl(semid,0,SETVAL,0) //Initialize value for semaphore 0
semctl(semid,1,SETVAL,0) //Initialize value for semaphore 0
writer_lock(semid) //writer lock
struct sembuf action[2] ;
action[0].sem_num = 0;
action[0].sem_flg = SEM_UNDO;
action[0].sem_op = 0 ;
action[1].sem_num = 1;
action[1].sem_flg = SEM_UNDO;
action[1].sem_op = +1 ;
semop(sem_id,action,2);
release_writer_lock
struct sembuf action[1] ;
action[0].sem_num = 1;
action[0].sem_flg = SEM_UNDO;
action[0].sem_op = -1 ;
semop(sem_id,action,1);
reader_lock(semid)
struct sembuf action[2] ;
action[0].sem_num = 1;
action[0].sem_flg = SEM_UNDO;
action[0].sem_op = 0 ;
action[1].sem_num = 0;
action[1].sem_flg = SEM_UNDO;
action[1].sem_op = +1 ;
semop(sem_id,action,2)
release_reader_lock
struct sembuf action[1] ;
action[0].sem_num = 0;
action[0].sem_flg = SEM_UNDO;
action[0].sem_op = -1 ;
semop(sem_id,action,1);
** writer end***
writer_lock(semid)
/* my work*/
release_writer_lock(semid)
** reader end***
reader_lock(semid)
/* read and clear */
release_reader_lock(semid)