Reputation: 75
I am trying to store all filenames in the current directory in a shared array using mmap I can print all 9 files in the directory to the screen but when I try to store them in the array (shared_array) and print the array, all entries contain the same string (file.txt). Thanks in advance!
char **shared_array;
shared_array= mmap(0,100*sizeof(char*),PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0);
char * filename;
const MAXLINE = 80;
char line [MAXLINE];
FILE *fp = popen("/bin/ls","r");
int i = 0;
while(fgets(line, MAXLINE,fp) !=NULL){
filename = line;
shared_array[i] = filename;
i++;
}
pclose(fp);
int j;
for(j=0;j<i;j++){
printf("\n%s",shared_array[j]);
}
Upvotes: 3
Views: 2257
Reputation: 41
If MAXLINE denotes total number of strings each of size N :-
You cannot do this. It will give a very long string of size MAXLINE X N and will have to use offset to access substrings.
char (*shared_memory)[MAXLINE] -> returns pointer to a string of size MAXLINE.
shared_array= mmap(0,100*MAXLINE,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0);
You need to do this
char *shared_memory[MAXLINE] - This returns array of char pointers
for(int i=0; i<MAXLINE;i++){
shared_memory[i] = mmap(NULL,sizeof(char)*N,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS,-1,0);
}
By doing this now you can access the strings by doing shared_memory[i]. Even though if each string is less then page granularity you will be wasting space but it will be easier to access.
or simply use
char shared_memory[100][MAXLINE];
Upvotes: 1
Reputation: 223699
When you do this:
filename = line;
shared_array[i] = filename;
You're not actually copying the contents of your line
array to shared_array
. You're assigning the address of line
to each array element. As a result, all array elements point to the same place, i.e. line
, which will only contain the most recently stored value.
You need to allocate memory for each string you want to copy. You could do that with strdup
:
shared_array[i] = strdup(line);
But the problem with this is that you have shared memory containing pointers to non-shared memory.
You'll need to allocate space in shared memory for an array of strings:
const MAXLINE = 80;
char (*shared_array)[MAXLINE];
shared_array= mmap(0,100*MAXLINE,PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANON,-1,0);
Then you can use strcpy
to copy into each array element:
strcpy(shared_array[i], line);
Upvotes: 4