0

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:

  1. When i re run the program, the file either resets or is written on top of
  2. 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
jonelearn
  • 13
  • 2
  • 9
  • Shouldn't `pos+=strlen(addr) + 1;` be `pos+=strlen(&addr[pos]) + 1;`? I don't see how this would cause your current output, but you probably shouldn't be adding the whole length of the string to `pos` for every substring you add. (Alternatively, `pos=strlen(addr) + 1;` but that's a bit less efficient...or use the fact that `sprintf` returns the number of `char`s added(not including `'\0'`)). Come to think of it, to get this output, you must be manipulating `pos` in some other way. The error likely lies in that code, if you want to update your question to include it. – lockcmpxchg8b Dec 09 '17 at 22:13
  • @lockcmpxchg8b yeah you're right about that. Meant to just put in `pos = strlen(addr) + 1;`. Strangely enough either produce the same result. – jonelearn Dec 09 '17 at 22:17
  • something has to be adjusting `pos` then. I'd search through the code for every update to `pos`, since it appears to be a global variable. I note in your example above that you update `pos` *after* you have released the mutex...that seems a bit dangerous. – lockcmpxchg8b Dec 09 '17 at 22:21
  • @lockcmpxchg8b `pos` starts globally at 0, and is only messed with the 2 times you see on the post and once another equal to that of the thread function. – jonelearn Dec 09 '17 at 22:33

0 Answers0