Shared Memory in IPC: Features and Creation
Classified in Computers
Written at on English with a size of 2.8 KB.
Common Features of IPC Light Mechanisms
These mechanisms are implemented as a unit and share common features, including:
- All mechanisms have a table whose entries describe their usage. Each table entry has a numerical key chosen by the user.
- Each mechanism has a 'get' call to create a new entry or retrieve an existing one. The parameters of this call include a key and a mask of flags. The kernel searches the table for an entry that matches the provided key.
- If the key is set to
IPC_PRIVATE
, the kernel occupies the first free entry. Subsequent calls will return this entry until it is released. - If the
IPC_CREAT
flag is active in the mask, the kernel creates a new entry if there is no match for the provided key. If bothIPC_CREAT
andIPC_EXCL
flags are active, the kernel returns an error if an entry already exists for the given key. - If everything works correctly, the kernel returns a descriptor that can be used in other calls.
- Each table entry has a record of permissions, including:
- User ID and process group that reserved the entry.
- User ID and group modified by the "control" of the IPC mechanism.
- A bit set with permissions for read, write, and execute for the user, group, and other users.
- Each entry contains status information, which includes the ID of the last process that used the entry.
Creating a Shared Memory Area for a Real Number Array
Here's an example of creating a shared memory area to store an array of floating-point numbers:
#define MAX 10
int shmid, i;
float *array;
key_t key;
// Generate a key
if ((key = ftok("test", 'k')) == (key_t)-1) {
perror("Error creating the key");
exit(1); // Added exit to prevent further execution on error
}
// Request shared memory
if ((shmid = shmget(key, MAX * sizeof(float), IPC_CREAT | 0600)) == -1) {
perror("Error in the request for shared memory");
exit(1); // Added exit
}
// Attach shared memory to the process
if ((array = (float *)shmat(shmid, 0, 0)) == (float *)-1) { // Corrected cast
perror("Error in attaching shared memory to our process");
exit(1); // Added exit
}
// Initialize the array
for (i = 0; i < MAX; i++) {
array[i] = i * i;
}
// Detach shared memory
if (shmdt((char *)array) == -1) {
perror("Error in detaching shared memory");
exit(1); // Added exit
}
// Remove shared memory
if (shmctl(shmid, IPC_RMID, 0) == -1) {
perror("Error in eliminating shared memory");
exit(1); // Added exit
}
Note: Error handling was improved by adding exit(1)
after each perror
call to prevent the program from continuing after a critical error. The cast in shmat
was also corrected.