简体   繁体   English

/dev/mem 文件描述符返回 0

[英]/dev/mem file descriptor returning 0

I am trying to access /dev/mem by mmap.我正在尝试通过 mmap 访问 /dev/mem。 I have disabled CONFIG_STRICT_DEVMEM in kernel config.我在内核配置中禁用了 CONFIG_STRICT_DEVMEM。 when I am trying to get the file descriptor fd, it always returns 0 which is the file descriptor for Standard input.当我尝试获取文件描述符 fd 时,它总是返回 0,这是标准输入的文件描述符。 What is going wrong here?这里出了什么问题?

#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/mman.h>
int main ()
{
        int fd =  -1;
        if(fd = open("/dev/mem",O_SYNC) < 0){
                printf("Error opening file \n");
                close(fd);
                return (-1);
        }
        else printf("/dev/mem fd: %d \n", fd);


        return 0;
}

output: /dev/mem fd: 0输出:/dev/mem fd:0

if(fd = open("/dev/mem",O_SYNC) < 0){

You've messed up the operator precedence.你搞砸了运算符的优先级。 That's parsed as这被解析为

fd = (open("/dev/mem",O_SYNC) < 0)

not as不像

(fd = open("/dev/mem",O_SYNC)) < 0

as you apparently expect.正如您所期望的那样。 Always compile with -Wall and don't ignore the warnings.始终使用-Wall进行编译,不要忽略警告。

According to the docs根据文档

Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor.成功完成后,该函数应打开文件并返回一个非负整数,表示编号最低的未使用文件描述符。 Otherwise, -1 shall be returned and errno set to indicate the error.否则,将返回 -1 并设置 errno 以指示错误。 No files shall be created or modified if the function returns -1.如果函数返回 -1,则不应创建或修改任何文件。

So 0 means there was no error.所以0表示没有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM