Search code examples
cmemoryshared

Do calls to shmget or shmat initialize data?


When using shared memory in c, is it possible to first create data and then attach it to the shared segment (something like initialization)? Or must I first create the shared segment and then attach data to it?

I do think that both ways are correct, but I am not sure of what is exactly happening during calls to shmget and shmat. Do any of these calls, initialize the attached data?


Solution

  • is it possible to first create data and then attach it to the shared segment?

    No.

    Or must I first create the shared segment and then attach data to it?

    Yes - you get the piece of memory, then you write/place data in it.

    shmat() gives you a pointer to the shared segment. When you assign that to an existing pointer in your program, that pointer points to this piece of memory.

    Do any of these calls, initialize the attached data?

    When creating a new shared memory segment, all bytes within it will be initialized to zero. When attaching a segment that already is created, you get whatever you placed in that segment previously.