的shm_open和ftruncate()在共享内存编程 [英] shm_open and ftruncate() in Shared Memory Programming

查看:825
本文介绍了的shm_open和ftruncate()在共享内存编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个共享内存对象,并将其截断为特定的大小。

I want to create a Shared Memory Object and truncate it to a specific size.

SHMSIZE与512定义

SHMSIZE is defined with 512

模式设置与S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH

MODE is set with S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH

下面是我的code

char *shm_name = "SharedMemory";    
int fd; 

/* Open an Shared Memory Object for Read-/Write-Access */    
if((fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE) < 0)) {     
     perror("\nshm_open() in Caretaker failed");    
     exit(EXIT_FAILURE);
}

/* Truncate Shared Memory Object to specific size */
if((ftruncate(fd, SHMSIZE) < 0)) {
    perror("\nftruncate() in Caretaker failed");
    exit(EXIT_FAILURE);
}

在调试我看了那的shm_open()的返回值为0每一次,但我可以看到的/ dev / shm的这个对象。但在执行ftruncate()返回错误无效的参数每一次。

While Debugging i watched that the return value of shm_open() is 0 every time, but i can see this object in /dev/shm. And while executing ftruncate() it returns every time with error "invalid argument".

为什么fd是0每次和为什么ftruncate不起作用?
我应该怎么办?

Why fd is 0 every time and why ftruncate doesn't work? What should i do?

推荐答案

业务在该语句的顺序是靠不住的:

The order of operations in this statement is wonky:

if((fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE) < 0)) {

您正在分配的shm_open(...)LT的结果; 0 FD ,这绝对不是你想要的。

You're assigning the result of shm_open(...) < 0 to fd, which is definitely not what you want.

移动比较​​括号外:

if((fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE)) < 0) {
                                                   ^^^

这篇关于的shm_open和ftruncate()在共享内存编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆