Re: madvise(MADV_FREE) doesn't work in some cases?

From: Vitaliy Gusev <gusev.vitaliy_at_gmail.com>
Date: Sat, 3 Jul 2021 11:34:50 +0300
> On 3 Jul 2021, at 09:54, Gary Jennejohn <gljennjohn_at_gmail.com> wrote:
> 
> The FreeBSD mail server apparently removed the attachment.
> 
> So either provide it in-line or put it on some pubic file server and
> add a link to it.
> 
> -- 
> Gary Jennejohn

#include <sys/mman.h>
#include <err.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
	size_t len = (size_t)(argc > 1 ? atoi(argv[1]) : 1024) * 1024 * 1024;
	uint8_t *ptr, *end, *p;
	unsigned pagesz = 1<<12;
	int pid;

	ptr = mmap(NULL, len, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	if (ptr == MAP_FAILED)
		err(1, "cannot mmap");

	end = ptr + len;
	printf("mmap %p pid %d\n", ptr, getpid());
	printf("end %p len %#lx\n", end, len);

	fflush(stdout);

	pid = fork();

	if (pid < 0)
		err(1, "cannot fork");

	printf("pid %d\n", getpid());

	sleep(pid == 0 ? 1 : 14);

	printf("%d: touch\n", getpid());

	p = ptr;
	while (p < end) {
		*p = 1;
		p += pagesz;
	}

	printf("%d: sleep before madvise\n", getpid());
	sleep(pid == 0 ? 1 : 4);
	printf("%d, madvise\n", getpid());

	p = ptr;
	while (p < end) {
		int error;

		error = madvise(p, pagesz, MADV_FREE);
		if (error) {
			err(1, "cannot madvise");
		}
		p += pagesz;
	}

	printf("%d: Press enter to exit\n", getpid());
	getchar();
}

——
Vitaliy Gusev
Received on Sat Jul 03 2021 - 08:34:50 UTC

Original text of this message