How it works...

By invoking the ftok function, we generate an IPC key with the filename sharedmem (you can change this) and an ID of a. The generated key is assigned to the key variable. Thereafter, invoke the shmget function to allocate a shared memory segment that is associated with the supplied key generated using the ftok function.

The size that's specified for the desired memory segment is 1024. Create a new memory segment with read and write permissions and assign the shared memory identifier to the shmid variable. Then, attach the shared memory segment to the first available address in the system.

Once the memory segment is attached to the address space, the segment's start address is assigned to the str variable. You will be asked to enter a string. The string you enter will be assigned to the shared memory segment through the str variable. Finally, the attached memory segment is detached from the address space.

Let's move on to the next part of this recipe, Reading a message from shared memory.