I have a program that needs to share a string between two processes. I have declared a struct that contains an array of *char
. This struct is allocated with shmget
and shmat
before the main process is forked.
typedef struct Queue
{
int index;
char *directory[10];
} Queue;
In one of the processes, I try to set the value: (data->dir_name
is a *char
to a string such as "/data1")
queue->directory[i] = data->dir_name; // Option 1
queue->directory[i] = "foo"; // Option 2
My question is, what is the difference between the first and second statements above? When setting the queue->directory[i]
to "foo"
, the other process sees it. However, passing the value data->dir_name
, it does not.
Thanks in advance!
The problem is you are only assigning a pointer, not copying the string data. In the first case you are setting the value to point to memory that the second process can't see. When you do the first line, the pointer data->dir_name
is put into queue->directory[i]
, but when the other process looks at that memory address within its own memory space, the data is not there. On the other hand, the second line puts the address of the static string "foo"
into the variable. Since the processes are compiled from the same source, that string is in the same place in each process's memory, so the second one can see it.
What you want to be doing is having a buffer in the struct that you strcpy
the directory name into. You'll need
char directory[10][200];
and
strcpy (queue->directory[i], data->dir_name);
You'll want to check that the string length is less than 200 (in this case), and report an appropriate error if it's too long. I'm not familiar with shared memory functions to know exactly how to do a malloc
equivalent; if you could do that; then you would copy the string into the malloc
ed shared memory and put the pointer to it in an array like you have in your code. From a very quick Google search though, it appears that malloc
ing shared memory like this might not work very well.