problem with shared memory
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 pr开发者_StackOverflowint just like if scanf is running
stdout
is line-buffered by default, which means that it is not flushed until a newline is printed. This means that you need to put \n
at the end of your "got mid"
, "got maddr"
and "messager 1"
strings, or fflush();
after those printf()
s.
By the way, SYSV shared memory is outdated. The POSIX mechanisms are significantly better designed - see shm_open()
and related calls.
Try adding a new line (\n
) at the end of all of your printf
statements. I assume it's failing before printing/flushing the buffer.
You can enter things in because the terminal is not blocking keystrokes, even though you haven't paused anywhere to read it. I regularly type in the "next thing" while my command-line/terminal is busy doing something else so that it just picks up when it's done. The stdin buffer can still accept the input. It just doesn't use it yet.
精彩评论