I am trying to access /dev/mem by mmap. I have disabled CONFIG_STRICT_DEVMEM in kernel config. when I am trying to get the file descriptor fd, it always returns 0 which is the file descriptor for Standard input. 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
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.
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. No files shall be created or modified if the function returns -1.
So 0
means there was no error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.