Tried to create shared memory block, and what I got is strange behaviour.
#include <sys/shm.h>
#include "stdio.h"
#include <sys/ipc.h>
int main() {
printf("starting\n");
int mid = -1;
mid = shmget((key_t)1234, 4096, IPC_CREAT|0666);
if(mid == -1) {
printf("cant get mid\n");
return 1;
} else {
printf("got mid");
}
int* maddr = 0;
maddr = shmat(mid, NULL ,0);
if(maddr == (int*)-1) {
printf("cant attach memory\n");
return 1;
} else {
printf("got maddr");
}
while(1) {
int cval = __sync_add_and_fetch(maddr, 1);
if(cval % 2) { // odd values
printf("messager 1");
sleep(1000);
}
}
}
If I try to execute that code, it prints starting and hangs, nothing more happens, but some why it accepts input from stdin, so I can print just like if scanf is running
stdoutis line-buffered by default, which means that it is not flushed until a newline is printed. This means that you need to put\nat the end of your"got mid","got maddr"and"messager 1"strings, orfflush();after thoseprintf()s.By the way, SYSV shared memory is outdated. The POSIX mechanisms are significantly better designed – see
shm_open()and related calls.