Date: Mon, 23 Jun 1997 10:48:48 -0700 (MST) From: Terry Lambert <terry@lambert.org> To: gurney_j@resnet.uoregon.edu Cc: freebsd-hackers@FreeBSD.ORG Subject: Re: problem with /dev/zero and mmap?? Message-ID: <199706231748.KAA00960@phaeton.artisoft.com> In-Reply-To: <19970623030040.50241@hydrogen.nike.efn.org> from "John-Mark Gurney" at Jun 23, 97 03:00:40 am
next in thread | previous in thread | raw e-mail | index | archive | help
> well.. I was just experimenting with mmap and discovered that something
> works when it shouldn't:
>
> fd=open("/dev/zero", O_RDONLY, 0);
> base=mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
> base[0]=4;
>
> the above won't cause a bus error.. but replace /dev/zero with a normal
> file and it will fail as expected (with a Bus error)... shouldn't the
> mmap behave the same?? if you try and write to the fd, it will set
> errno to EBADF, just like the man page says...
>
> well... I am looking at sys/vm/vm_mmap.c, and it looks like that special
> hack for SunOS (on line 228) is a bit to early... or does sunos require
> that you be able to do the above?
>
> I know it's minor, but it encorages bad programming, and someone might
> use code similar to the above and wonder why it stops working when they
> switch to a normal file, or other char device...
This use of /dev/zero is a "well known hack" for obtaining zero
filled anonymous pages from swap.
When you map pages from /dev/zero, you create a mapped page address
range which, even though it is MAP_SHARED is local only to your
process (you *can* cause child processes to inherit a shared
copy of this region using rfork() to implement your "fork()"
instead of calling it directly).
The write succeeds because pages you mapped are not associated with
the fd after the mapping.
This technique is frequently used on "mediaum model" OS's to get
contiguous buffers in excess of the 64k limit.
If things behaved as you wanted, there would be two possible
consequences:
1) You would modify the contents of /dev/zero for other
users of the device. This is not acceptable.
2) The mmap() would fail because of the conflict between
O_RDONLY and PROT_WRITE.
Either of these would render your request useless, since you
can get "read-only zeros" much easier using memset()/mprotect().
Regards,
Terry Lambert
terry@lambert.org
---
Any opinions in this posting are my own and not those of my present
or previous employers.
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199706231748.KAA00960>
