qa_ipc_shmem_lowlevel.cpp
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033 #include <sys/ipc.h>
00034 #include <sys/shm.h>
00035 #include <errno.h>
00036 #include <iostream>
00037 #include <signal.h>
00038
00039 using namespace std;
00040 using namespace fawkes;
00041
00042 #define SHMEM_SIZE 2048
00043 #define SHMEM_TOKEN "JustSomeDumbQA"
00044
00045 typedef struct {
00046 void *ptr;
00047 } header_t;
00048
00049 bool quit = false;
00050
00051 void
00052 signal_handler(int signum)
00053 {
00054 quit = true;
00055 }
00056
00057 int
00058 main(int argc, char **argv)
00059 {
00060
00061 signal(SIGINT, signal_handler);
00062
00063 key_t key = ftok(".", 'b');
00064 printf("Key: 0x%x\n", key);
00065
00066 if ( argc == 1 ) {
00067
00068 int shmid = shmget(key, SHMEM_SIZE, IPC_CREAT | 0666);
00069 if ( shmid == -1 ) {
00070 perror("M: Could not get ID");
00071 exit(1);
00072 }
00073
00074 void *shmem = shmat(shmid, NULL, 0);
00075 if ( shmem == (void *)-1 ) {
00076 perror("M: Could not attach");
00077 exit(2);
00078 }
00079
00080 memset(shmem, 0, SHMEM_SIZE);
00081
00082 header_t *header = (header_t *)shmem;
00083 header->ptr = shmem;
00084
00085 printf("M: ptr=0x%lx\n", (long unsigned int)shmem);
00086
00087 while ( ! quit ) {
00088 usleep(100000);
00089 }
00090
00091 shmctl(shmid, IPC_RMID, NULL);
00092 shmdt(shmem);
00093
00094 } else {
00095
00096 int shmid = shmget(key, SHMEM_SIZE, 0);
00097
00098 if ( shmid == -1 ) {
00099 perror("S: Could not get ID");
00100 exit(1);
00101 }
00102
00103 void *shmem = shmat(shmid, NULL, 0);
00104 if ( shmem == (void *)-1 ) {
00105 perror("S: Could not attach");
00106 exit(2);
00107 }
00108
00109 header_t *header = (header_t *)shmem;
00110
00111 printf("S: ptr=0x%lx header->ptr=0x%lx\n", (long unsigned int)shmem,
00112 (long unsigned int)header->ptr);
00113
00114 if ( shmem != header->ptr ) {
00115 printf("S: pointers differ, re-attaching\n");
00116 void *ptr = header->ptr;
00117 shmdt(shmem);
00118 shmem = shmat(shmid, ptr, SHM_REMAP);
00119 if ( shmem == (void *)-1 ) {
00120 perror("S: Could not re-attach");
00121 exit(3);
00122 }
00123 header = (header_t *)shmem;
00124 printf("S: after re-attach: ptr=0x%lx header->ptr=0x%lx\n",
00125 (long unsigned int)shmem, (long unsigned int)header->ptr);
00126 }
00127
00128
00129
00130
00131
00132
00133
00134 shmdt(shmem);
00135 }
00136
00137 return 0;
00138 }
00139
00140