Anonymous mmap

Portability

In short to use mmap with anonymous memory portably, use -1 as the fd argument; Linux igores it and BSD requires it so you meet both criteria.

Linux

As seen in the system call handler for mmap (taken from arch/ia64/kernel/sys_ia64.c), for an anonymous mmap the fd is ignored.

do_mmap2 (unsigned long addr, unsigned long len, int prot, int flags, int fd, unsigned long pgoff)
{
        unsigned long roff;
        struct file *file = 0;

        flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
        if (!(flags & MAP_ANONYMOUS)) {                    <- if MAP_ANONYMOUS we ignore the fd argument
                file = fget(fd);
                if (!file)
                        return -EBADF;

                if (!file->f_op || !file->f_op->mmap) {
                        addr = -ENODEV;
                        goto out;
                }
        }

 ....

FreeBSD

As seen in vm/vm_mmap.c on FreeBSD, the fd argument must be -1 for an anonymous mmap

int
mmap(p, uap)
        struct proc *p;
        register struct mmap_args *uap;
{
        
     ...

        /* make sure mapping fits into numeric range etc */
        if ((ssize_t) uap->len < 0 ||
            ((flags & MAP_ANON) && uap->fd != -1))
                return (EINVAL);

IA64wiki: AnonymousMmap (last edited 2009-12-10 03:13:50 by localhost)

Gelato@UNSW is sponsored by
the University of New South Wales National ICT Australia The Gelato Federation Hewlett-Packard Company Australian Research Council
Please contact us with any questions or comments.