简单地将一个整数存储在共享内存段中:C
我只是想在两个进程之间共享一个整数,但是内存段在程序 1 中初始化并在程序 4 中使用。这是程序 1 中的初始化:
shmid = shmget(key, sizeof(int*), 0666 | IPC_CREAT);
int *data = (int *)shmat(shmid, (void*)0,0);
这里我收到一条警告“从不同大小的整数转换为指针” ”。啊。
我想这很简单,但我对 IPC 是个菜鸟。还有 c 中的许多其他内容...
然后我将其传递给另一个程序:
snprintf(shmarg, sizeof(shmarg), "%n", data);
pid_t pid3 = run_cmd4("/home/tropix/hw11-4", shmarg, semarg, pipe_from_p2_2, pipe_to_p5_2);
但不确定如何在另一端访问它。如何在程序 4 中取回 int 值?
Im just trying to share an integer between two processes, but the memory segment is initialized in program 1 and is used in program 4. Here is the initialization in program 1:
shmid = shmget(key, sizeof(int*), 0666 | IPC_CREAT);
int *data = (int *)shmat(shmid, (void*)0,0);
Here I get a warning of "cast to pointer from integer of different size". Argh.
Simple, I'm assuming, but I'm a big time noob with IPC. And many other things in c....
Then I pass it to another program:
snprintf(shmarg, sizeof(shmarg), "%n", data);
pid_t pid3 = run_cmd4("/home/tropix/hw11-4", shmarg, semarg, pipe_from_p2_2, pipe_to_p5_2);
Not sure how to access it on the other side though. How can I get the int back in Program 4?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很确定您缺少定义
shmat()
的标头,因此编译器猜测shmat
返回一个 int (而不是指针)。Pretty sure you're missing the header that defines
shmat()
and thus the compiler is guessing thatshmat
returns an int (not a pointer).尝试使用 NULL 而不是
(void*)0
。指针本身没有用,除非共享内存区域恰好加载到另一个程序中完全相同的虚拟内存地址:您可能甚至不想尝试安排它 - 相反,让另一个程序(hw11- 4) 加载共享内存段并让操作系统选择虚拟内存地址,然后简单地查看该地址中的
int
。因此,hw11-4
需要传递相同的共享内存密钥(例如作为命令行参数),并且它本身使用shmget
打开并获取密钥,然后< code>shmat 来映射,将共享内存段映射到内存中....Try using NULL instead of
(void*)0
.The pointer itself isn't useful unless the shared memory area happens to be loaded at the exact same virtual memory address in the other program: you probably don't even want to try to arrange that - instead, let the other program (hw11-4) load the shared memory segment and let the OS choose the virtual memory address, then simply look at that address for the
int
. So,hw11-4
needs to be passed the same shared memory key (e.g. as a command line argument) and itself useshmget
to open and get the key for, thenshmat
to map, the shared memory segment into memory....