I am working on a POSIX-based program that shares a memory object between two or more processes, aka a Server - Client program.
I have some issues with the Server side of the program. I know how to map memory using mmap()
and how to work with the Object between two different processes/programs. However, I have an issue when adding an array of integers to a shared memory object.
I can use sprintf()
to print the contents to the shared memory object, then increase (reallocate) space of the Shared Memory Object by simply saying ptr += strlen(whatstringiamworkingwith);
However, I do not know how to re-allocate memory to the object when it contains an array of integers in C. Here is my program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int *calcCollatz(int n) {
int solution;
int *collatzSeq = malloc(sizeof(int));
int j = 0;
while (n != 1) {
if (n % 2 == 0) {
solution = n / 2;
n = solution;
collatzSeq[j] = n;
j++;
return collatzSeq;
} else {
solution = (3 * n) + 1;
n = solution;
collatzSeq[j] = n;
j++;
return collatzSeq;
}
}
}
int main(int argc, char *argv[])
{
const int SIZE = 4096; //size in bytes of Shared Memory Object
const char *sharedObj = "Shm"; //name of the Shared memory Object
int shm_fd; //Shared memory file descriptor
void *ptrShm; //Pointer to shared memory object
shm_fd = shm_open(sharedObj, O_CREAT | O_RDWR, 0666); //Create Shared Memory Object
ftruncate(shm_fd, SIZE); //configure the size of the shared memory object
//Map the shared memory object in the space of the process
ptrShm = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (ptrShm == MAP_FAILED) {
printf("Map Failed\n");
return -1;
}
sprintf(ptrShm, argv[1]);
ptrShm += strlen(argv[1]);
sprintf(ptrShm, calcCollatz(atoi(argv[1])));
ptrShm += sizeof(calcCollatz(atoi(argv[1])));
printf("Writing the sequence to a shared memory object!\n");
return 0;
}
Am I even on the right track?