Ashikee AbHi
Ashikee AbHi

Reputation: 395

/dev/mem file descriptor returning 0

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

Upvotes: 0

Views: 1045

Answers (2)

user10678532
user10678532

Reputation:

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.

Upvotes: 4

Diego Torres Milano
Diego Torres Milano

Reputation: 69398

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.

Upvotes: 1

Related Questions