1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include <iostream>
#include <string>
#include <cstdlib>
// Shared memory
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
// Gestion des erreurs
#include <errno.h>
using namespace std;
int main(int argc, const char *argv[]) {
switch (atoi(argv[1])) {
case 25 : { // Test shared memory with shm_open & mmap - http://kahdev.wordpress.com/2010/05/15/using-shared-memory-in-linux-programming/
int *result = NULL;
int integerSize = sizeof(int);
// Open the shared memory - "manager"
int descriptor = shm_open("/test25", O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
if (errno == EEXIST) {
cout << "Instance : " << argv[2] << " - The exchange file test25 already exists" << endl;
}
if (descriptor == -1) {
cout << "Instance : " << argv[2] << " has failed." << endl;
exit errno;
}
/* Size up the shared memory. */
if (ftruncate(descriptor, integerSize) != 0){
cout << "Instance : " << argv[2] << " - ftruncate has failed with error code : " << errno << endl;
exit errno;
}
result = (int*) mmap(NULL, integerSize, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_LOCKED | MAP_POPULATE, descriptor, 0 );
if (result == MAP_FAILED) {
cout << "Instance : " << argv[2] << " - mmap failed with error code : " << errno << endl;
exit errno;
}
// Init the shared memory
*result = 161803;
string endCondition = "";
while (endCondition != "quit") cin >> endCondition;
// clean
if (munmap(result, sizeof(int)) != 0) {
cout << "Instance : " << argv[2] << " - munmap has failed with error code : " << errno << endl;
exit errno;
}
if (shm_unlink("/test25") != 0) {
cout << "Instance : " << argv[2] << " - shm_unlink has failed with error code : " << errno << endl;
exit errno;
}
break;
}
case 26 : { // Test shared memory with shm_open & mmap
int *result = NULL;
int integerSize = sizeof(int);
// Open the shared memory - "user"
int descriptor = shm_open("/test25", O_RDONLY, S_IRUSR);
if (errno == ENOENT) {
cout << "Instance : " << argv[2] << " - The exchange file test25 does not exist" << endl;
}
if (descriptor == -1) {
cout << "Instance : " << argv[2] << " has failed." << endl;
exit errno;
}
result = (int*) mmap(NULL, integerSize, PROT_READ, MAP_SHARED, descriptor, 0 );
if (result == MAP_FAILED) {
cout << "Instance : " << argv[2] << " - mmap failed with error code : " << errno << endl;
exit errno;
}
cout << "Value = " << *result << endl;
if (munmap(result, sizeof(int)) != 0) { // unnecessary because the program exits - cf http://www.advancedlinuxprogramming.com/alp-folder/alp-ch05-ipc.pdf
cout << "Instance : " << argv[2] << " - munmap has failed with error code : " << errno << endl;
exit errno;
}
// shm_unlink("/test25"); // As I undersqtand it, that should be performed only by the "manager"
break;
}
}
return 0;
}
|