Re: Help on mmap (with pointers)
From: Nissan 350Z (none_at_none.com)
Date: 02/25/04
- Next message: Tim: "Is timex broken on hpux 11.0?"
- Previous message: Neil Smyth: "New migration solution to salvage HP Interface Architect based Motif applications"
- In reply to: mshetty: "Help on mmap (with pointers)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 25 Feb 2004 21:29:36 +0100
> If I have a data structure with pointers that want to memory map into
> a file. How exactly do I do this?
>From HP ITRC:
Date: 3/9/95
Document description: Example of a program using a memory mapped file
Document id: UNX1000079
Problem Description
How is the coding of a program to use a memory mapped file?
Solution
Here's two programs that share a memory-mapped file. The file is exactly
the size of 10 integers. The programs map the file and use it as if it
were a 10-member array of integers in memory. One program writes into the
array and the other reads from the array; since the file is mapped with
the MAP_SHARED flag, the processes share the updates:
--------------
Writer process
--------------
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
main()
{
int *stuff;
int myfd;
/* create a file of the proper length, if needed */
if (access("/tmp/tenints", F_OK) != 0)
{
if (creat("/tmp/tenints", 0660) == -1)
{
perror("Can't create");
exit(1);
}
if (truncate("/tmp/tenints", 10*sizeof(int)) == -1)
{
perror("Can't truncate");
exit(1);
}
}
/* open the file */
if ((myfd = open("/tmp/tenints", O_RDWR)) == -1)
{
perror("Can't open");
exit(1);
}
/* mmap it and treat it as an array of integers */
if ((stuff = (int *)mmap(0, 10*sizeof(int), PROT_READ|PROT_WRITE,
MAP_FILE|MAP_SHARED|MAP_VARIABLE, myfd, 0)) == -1)
{
perror("Can't mmap");
exit(1);
}
srand(time(0));
/* write in random places in the file using normal array syntax */
for(;;)
{
int nextind = rand() % 10;
int nextval = rand();
stuff[nextind] = nextval;
printf("Writing %d at index %d\n", nextval, nextind);
sleep(2);
}
}
--------------
Reader process
--------------
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
main()
{
int *stuff;
int myfd;
if ((myfd = open("/tmp/tenints", O_RDONLY)) == -1)
{
perror("Can't open");
exit(1);
}
if ((stuff = (int *)mmap(0, 10*sizeof(int), PROT_READ,
MAP_FILE|MAP_SHARED|MAP_VARIABLE, myfd, 0)) == -1)
{
perror("Can't mmap");
exit(1);
}
srand(time(0));
for(;;)
{
int nextind = rand() % 10;
int nextval = stuff[nextind];
printf("Reading %d at index %d\n", nextval, nextind);
sleep(2);
}
}
- Next message: Tim: "Is timex broken on hpux 11.0?"
- Previous message: Neil Smyth: "New migration solution to salvage HP Interface Architect based Motif applications"
- In reply to: mshetty: "Help on mmap (with pointers)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|