Basically – I want to put a singular int
, and an array of the following structures:
struct My_structure {
char my_text[200];
char my_name[20];
int my_number;
};
Into a shared memory segment (IPC System V) obtained through shmat
. However, I don’t quite have an idea how to achieve that.
First of all, is it even possible to have the unrelated int
and the array in one segment, or would I have to separate them? How would this separation work? shmget
and shmat
one time more just for that int
?
Second – how to actually write it with shmat so I can handle errors? I’ve seen some examples of people using shmat with char (but no error handling) and with int (with error handling), but a struct obviously can’t be in the negatives (the links below are what I saw).
https://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html
https://www.geeksforgeeks.org/ipc-shared-memory/
In the current state of the code, I get a warning for trying to compare a pointer and integer:
warning: comparison between pointer and integer
55 | if ((shm_pointer = (struct My_structure *) shmat(shm_id, NULL, 0)) == -1){
|
Third – how to make the “insides” of the shared memory an array? Or really anything that’d function similarly enough to an array, I need to be able to do array[number]
in some shape or form.
Below is a snippet of code relevant to the question:
//those two lines before the problematic one seem to work right
//im pretty sure i wouldnt declare the array beforehand in the final version, its just more practical at this stage of writing the code
if ((key = ftok(argv[1],2137)) == -1){/*error handling*/}
if ((shm_id = shmget(key, sizeof(array_of_structs) + sizeof(unrelated_singular_int), 0644 | IPC_CREAT)) == -1){/*error handling*/}
//cant quite wrap my head around it
if ((shm_pointer = (struct My_structure *) shmat(shm_id, NULL, 0)) == -1){/*error handling*/}