Alex Castillo Alex Castillo - 1 month ago 8
C Question

Store an string on a Shared Memory C

Hi this code is working fine storing on a shared memory integers, but i want to store strings, how can i modify it to do that?

For example the output will be Written: This is the line number 1 and in the next line Written: This is the line number 2

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <sys/shm.h>
#include <unistd.h>


void main()
{
key_t Clave;
int Id_Memoria;
int *Memoria = NULL;
int i,j;



Clave = ftok ("/bin/ls", 33);
if (Clave == -1)
{
printf("No consigo clave para memoria compartida");
exit(0);
}


Id_Memoria = shmget (Clave, 1024, 0777 | IPC_CREAT);
if (Id_Memoria == -1)
{
printf("No consigo Id para memoria compartida");
exit (0);
}


Memoria = (int *)shmat (Id_Memoria, (char *)0, 0);
if (Memoria == NULL)
{
printf("No consigo memoria compartida");
exit (0);
}



for (j=0; j<100; j++)
{
Memoria[j] = j;
printf( "Written: %d \n" ,Memoria[j]);
}




shmdt ((char *)Memoria);
shmctl (Id_Memoria, IPC_RMID, (struct shmid_ds *)NULL);
}

Answer

You need to copy string character by character to shared memory. Actual pointer pointing to the variable in shared memory needs to stay outside because shared memory can be in different addresses in different process. (You could use delta pointers but they are a lot easier in C++ boost::offset_ptr)

For manipulating strings there is string utility functions in string.h. Specially strncpy would be useful when moving strings to different memory locations.

Also it would be good idea to use new posix shared memory instead of your current sysv implementation. You can see more details about posix shared memory in shm_overview man page. Of course if you have an old OS that supports only sysv interface then you have to stick with old api.

Comments