0

I would to ask you, how initiate array in struct for size from keyboard(argv) with shared memory, I can't use malloc, because it initiate's privat or something like that.

For example piece of code

Struct with array which I want initiate

struct data
{
  char txt[size from keyboard];
};

How to resize this array, remembering that we will use shared memory IPCV?

Thanks form your help :)

edit:

so if I had one more variable in struct, Can I do it like this?

struct data
{
   int counter; 
   char *text;
}*shared data;

int shmid

int main(int argc, char* argv[])
{
  int m = atoi(argv[1]) /* number of slots*/ 
  int n = atoi(argv[2]) /*size of txt */

  shmid = shmget(12345, m * n * sizeof(struct my_data), IPC_CREAT|)600|IPc_EXCL)); 

shared_data = (struct data*)shmat(shmid, NULL, 0);

/*So now Can I write to txt??? */


}

1 Answer 1

1

Change txt from char[] to char*, and then use shm_open() and mmap() to allocate shared memory once you know the desired size.

typedef struct data
{
  char *txt;
} data;

data d;
int shm_fd = shm_open("name", O_RDWR | O_CREAT);
d.txt = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
...
munmap(d.txt, size);
shm_unlink("name");
Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to it in IPCV? I ask, because shm_open and mmap are POSIX
@Roundstic I don't know what IPCV is
linux System V IPC
According to this, System V has another API for shared memory, so just replace shm_open()/mmap()/munmap()/shm_unlink() in my example with shmget()/shmat()/shmdt/shmctl() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.