I'm trying to log the activity of my program using memory mapped files. The file is created fine, and i can't write to it as well, however i've encountered two problems:
- When i re run the program, the file either resets or is written on top of
- The string i print on it is not written in it's entirity.
here's where i create the file:
void create_log(){
flog = open(LOG, O_RDWR | O_CREAT ,0666);
if(flog < 0){
if(errno!=EEXIST){
perror("Couldn't open log for writing");
exit(0);
}
}
if(lseek(flog, MMF, SEEK_SET) < 0){
perror("lseek");
exit(0);
}
if(write(flog,"", 1) < 0){
perror("Couldn't expand flog");
exit(0);
}
if((addr = mmap(NULL, MMF,PROT_READ|PROT_WRITE,MAP_SHARED,flog,0)) == MAP_FAILED){
perror("mmap");
}
sprintf(&addr[pos],"##NEW LOG##\n");
pos+=strlen(addr) + 1;
}
and here's an instance of where i write to it:
void threads(){
int i;
for(i=0;i<data.triage;i++){
tid[i] = i;
pthread_create(&thread[i],NULL,worker,&tid[i]);
pthread_mutex_lock(&mutex);
sprintf(&addr[pos],"Triage %d opened\n",i);
pos = strlen(addr) + 1;
pthread_mutex_unlock(&mutex);
}
}
With only this 2 sprintfs
the log file results in:
##NEW LOG##
Triage 0 openTriage 1 openTriage 2 openTriage 3 openTriage 4 opened\n