Hi, I'm looking at shared memory in C and I seem to have encountered a bit of a problem. I'm fairly sure that I may be misunderstanding something here. I'm trying to send an array of structs to another process via shared memory. When the other process goes to read it, it just reads nothing.

I'm using ubuntu.

Process that creates it:

//create shared memory segment
key_t key;
key = 12;
int shmid = shmget(key, 4096, IPC_CREAT | 0666);

//Attach the shared memory segement


//Create aux file

FILE * pFile;
pFile = fopen("part4.aux", "w+");
fprintf(pFile, "%s", "Here are the first 10 strings that were transmitted.\n");



//Write 10,000 random strings to the shared memory segment
//Also write to file to prove what has been transmitted

Data sharedmem[10000];

int i = 0;

for(i = 0; i < 10000; i++){
	Data d;
	d.c1 = alpha[rand()%(sizeof(alpha)-1)];
	d.c2 = alpha[rand()%(sizeof(alpha)-1)];
	d.c3 = alpha[rand()%(sizeof(alpha)-1)];
	d.c4 = alpha[rand()%(sizeof(alpha)-1)];
	

	if(i < 10){
	fprintf(pFile, "\n");
	fprintf(pFile, "%c", d.c1);
	fprintf(pFile, "%c", d.c2);
	fprintf(pFile, "%c", d.c3);
	fprintf(pFile, "%c", d.c4);
	}

	sharedmem[i] = d;
	}

Data* pointer = (Data*)shmat(shmid,0,0);
fprintf(pFile, "\n%s\n", "Production complete.");

pointer = sharedmem;

fclose(pFile);
shmdt(pointer);

Process attempting to read it.

//Find shared memory segment
key_t key;
key = 12;
int shmid = shmget(key, 4096, 0666);

//Attach the shared memory segement
Data* shared_memory = (Data*) shmat(shmid, 0, 0);

//Open aux file 

FILE * pFile;
pFile = fopen("part4.aux", "a+");
fprintf(pFile, "%s", "Here are the strings that were received.\n");

//Read strings from shared memory

printf("%s\n", "Writing to file");

int i;

for(i = 0; i < 10; i++){
   fprintf(pFile, "%c", shared_memory[i].c1);
   fprintf(pFile, "%c", shared_memory[i].c2);
   fprintf(pFile, "%c", shared_memory[i].c3);
   fprintf(pFile, "%c", shared_memory[i].c4);
   fprintf(pFile, "\n");
 //fputc(shared_memory[i].c1, pFile);
 //printf("%c", shared_memory[i].c1);
 
}


//fprintf(pFile, "%s", shared_memory);

printf("%s\n", "Closing file");
fclose(pFile);
shmdt(shared_memory);

If anybody could shed any light on where I'm going wrong, that would be much appreciated.

Other notes:
- When reading the memory seg and printing to file, it doesn't like being printed as "%s" because it thinks the data is an int.
- It doesn't mind "%c" however, but it makes the file unreadable. However, when ran in cent os, the file is readable but displays (null) (null) (null) (null)

pointer = sharedmem; is pointer assignment. You will want to do a memcpy to have that work the way you'd like.

Ahhh, thank you! It works now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.