Thread: mmap fails with errno EBADF

  1. #1
    Registered User
    Join Date
    Oct 2006

    mmap fails with errno EBADF

    In my program I am opening a file as follows:

    std::string filename = "somefile";
    struct stat st;
    stat(filename.c_str(), &st);
    int fd = open(filename.c_str(), O_RDONLY);
    the open succeeds, and gives me a valid file number.
    I then attempt to memory-map the file using mmap() as follows:

    unsigned char* buf = (unsigned char*)mmap(NULL, st.st_size, PROT_READ, fd, MAP_PRIVATE | MAP_POPULATE, 0);
    I then check the return value of mmap() and find that it is equal to MAP_FAILED. I print the return value of strerror(errno) to stdout and it says "Bad file descriptor."

    the file is exactly 51200000 bytes long (an integer multiple of the 4096 byte page size), and I'm not asking it to map to a specific or non-aligned memory address.

    not sure what I'm doing wrong here, but I just can't seem to make this work.

    system is OpenSuse 10.3 x86 kernel version
    2GB of system memory + 4GB swap
    GCC version 4.2.1
    Last edited by Elkvis; 09-10-2009 at 09:30 AM. Reason: add more info

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    You got your parameters to mmap() mixed up.


  3. #3
    Registered User
    Join Date
    Oct 2006
    thanks! it would have taken me many hours to spot that, being inexperienced with mmap and its friends.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    This is all I've ever done with mmap(), but it worked:

    seeking for exercises

    Looking at that, it appears I used a file opened O_RDWR|O_CREAT, not O_RDONLY, but since your mmap call is PROT_READ I guess that should be okay. The other difference is in the flags at the end...which it looks to me like you have the flags parameter and the fd parameter backward!
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. errno function, error TLS/non TLS
    By fran.b in forum C Programming
    Replies: 13
    Last Post: 03-25-2009, 08:06 AM
  2. BSD mmap for shared memory - am I right?
    By sean in forum Linux Programming
    Replies: 21
    Last Post: 03-09-2009, 01:57 PM
  3. using mmap for copying large files
    By rohan_ak1 in forum C Programming
    Replies: 6
    Last Post: 05-13-2008, 08:12 AM
  4. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM