Hi All
I'm a C++ noob so please don't be too harsh. I have written a tiny server using sockets. It forks children off for each connection. Trouble is I need have each child report back to the parent. I have been trying to set up a shared file using mmap (I'm not married to this idea though).
Problem I'm having is that the map->push_back(myRequestLog); fails without any error or any feedback.
If anyone can give me some pointers I would appreciate it.
int writeSharedMemory(RequestLog myRequestLog){
int i;
int fd;
int result;
bool existed = true;
vector<RequestLog> *map; /* mmapped array of RequestLog's */
/* Open a file for writing. */
fd = open(FILEPATH, O_RDWR, (mode_t)0600);
if (fd == -1) {
existed = false;
fd = open(FILEPATH, O_RDWR | O_CREAT, (mode_t)0600);
if (fd == -1) {
perror("Error opening file for writing");
exit(EXIT_FAILURE);
}
}
if(!existed){
/* Stretch the file size to the size of the (mmapped) vector*/
result = lseek(fd, FILESIZE-1, SEEK_SET);
if (result == -1) {
close(fd);
perror("Error calling lseek() to 'stretch' the file");
exit(EXIT_FAILURE);
}
result = write(fd, "", 1);
if (result != 1) {
close(fd);
perror("Error writing last byte of the file");
exit(EXIT_FAILURE);
}
}
/* Now the file is ready to be mmapped.*/
map = (vector<RequestLog>*)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
/* Now write int's to the file as if it were memory*/
try{
map->push_back(myRequestLog);
} catch (const Error &error) {
cout << error.get_msg() << "\n";
}
/* Don't forget to free the mmapped memory*/
if (munmap(map, FILESIZE) == -1) {
perror("Error un-mmapping the file");
/* Decide here whether to close(fd) and exit() or not. Depends... */
}
/* Un-mmaping doesn't close the file, so we still need to do that.*/
close(fd);
return 0;
}