My task is to create shared memory by using a program. It writes string from command line argument to shared memory section. It will be then read by another program. I'm using structure to create shared memory. Now, my questions is I’m not able to pass strings which were given in command line into structure variable. How can I write multiple strings into one array of pointers of char variable?
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <malloc.h>
#include "shm-com.h"
void main(int argc,char *argv[])
{
key_t shmKey;
int shm_id,i,j=0;
struct memory *dataptr;
char *string[10];
shmKey = ftok(".",1234);
printf("no. of strings %d\n",argc);
shm_id = shmget(shmKey,sizeof(struct memory),0666 | IPC_CREAT);
if(shm_id < 0)
{
perror("shm_id didn't create\n");
exit(0);
}
dataptr = (struct memory *)shmat(shm_id,NULL,0);
if((int) dataptr == -1)
{
perror("****didn't attatch to share memory\n");
}
printf("share memory attatched at %p address\n",dataptr);
dataptr->status = NOT_READY;
for(i = 1;i < argc;i++)
{
string[j] = argv[i];
j++;
}
printf("data attached to share memory\n");
for(i = 0;i < argc ; i++)
{
printf("%s\n",string[i]);
}
for(i = 0;i < argc;i++)
{
strcpy(dataptr->data[i],argv[i]);
}
dataptr->status = FILLED;
printf("please start client window\n");
while(dataptr != TAKEN);
sleep(1);
shmdt((void *)dataptr);
printf("server has detached sharre memory\n");
shmctl(shm_id,IPC_RMID,NULL);
printf("server cancelled shared memroy\n");
exit(0);
}
and my structure file name shm-com.h is
#define TAKEN 1
#define FILLED 0
#define NOT_READY -1
struct memory
{
char *data[10];
int status;
};