#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <err.h>
int
main(int argc, char *argv[])
{
int fd;
char *mem;
char *tmpfile;
char teststring[] = "hello, world!\0";
int rc;
char c0;
int status;
tmpfile = tmpnam(NULL);
fd = open(tmpfile, O_RDWR | O_CREAT | O_TRUNC, 0777);
if (fd == -1)
err(1, "open/creat failure");
unlink(tmpfile);
write(fd, teststring, strlen(teststring));
fsync(fd);
mem = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (mem == MAP_FAILED)
err(1, "mmap failure");
rc = strcmp(mem, teststring);
if (rc != 0)
err(1, "unexpected map region");
rc = mprotect(mem, 4096, PROT_NONE);
if (rc == -1)
err(1, "mprotect error");
rc = madvise(mem, 4096, MADV_WILLNEED);
if (rc == -1)
err(1, "madvise failed");
rc = fork();
if (rc == 0) {
c0 = mem[0];
if (c0 == 'h')
exit(0);
exit(1);
}
wait(&status);
rc = 0;
if (WIFEXITED(status)) {
rc = -1;
}
if (WIFSIGNALED(status)) {
rc = 0;
}
munmap(mem, 4096);
close(fd);
printf("%d \n", rc);
return (rc);
}