共享内存问题
尝试创建共享内存块,但我得到的是奇怪的行为。
#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);
}
}
}
如果我尝试执行该代码,它会打印开始并挂起,不会再发生任何事情,但有些原因是它接受来自标准输入的输入,因此我可以像 scanf 正在运行一样进行打印
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
stdout
默认情况下是行缓冲的,这意味着在打印换行符之前它不会被刷新。这意味着您需要将\n
放在"got mid"
、"got maddr"
和"messager 的末尾1"
字符串,或printf()
之后的fflush();
。顺便说一下,SYSV 共享内存已经过时了。 POSIX 机制的设计明显更好 - 请参阅
shm_open()
和相关调用。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, 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.尝试在所有
printf
语句的末尾添加一个新行 (\n
)。我认为它在打印/刷新缓冲区之前失败了。您可以输入内容,因为终端不会阻止击键,即使您没有在任何地方暂停来阅读它。当我的命令行/终端忙于做其他事情时,我经常输入“下一件事情”,这样它就会在完成后恢复。标准输入缓冲区仍然可以接受输入。它只是还没有使用它。
Try adding a new line (
\n
) at the end of all of yourprintf
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.