Creating a mapped data file with the shmat subroutine
This section describes how to create a mapped data file using shmat subroutine.
Prerequisite condition
The file to be mapped is a regular file.
Procedure
The creation of a mapped data file is a two-step process. First, you create the mapped file. Then, because the shmat subroutine does not provide for it, you must program a method for detecting the end of the mapped file.
- To create the mapped data file:
- Open (or create) the file and save the file descriptor:
if( ( fildes = open( filename , 2 ) ) < 0 ) { printf( "cannot open file\n" ); exit(1); }
- Map the file to a segment with the shmat subroutine:
The SHM_MAP constant is defined in the /usr/include/sys/shm.h file. This constant indicates that the file is a mapped file. Include this file and the other shared memory header files in a program with the following directives:file_ptr=shmat (fildes, 0, SHM_MAP);
#include <sys/shm.h>
- Open (or create) the file and save the file descriptor:
- To detect the end of the mapped file:
- Use the lseek subroutine to go to the end of file:
This example sets the value of eof to an address that is 1 byte beyond the end of file. Use this value as the end-of-file marker in the program.eof = file_ptr + lseek(fildes, 0, 2);
- Use file_ptr as a pointer to the start of the data file,
and access the data as if it were in memory:
while ( file_ptr < eof) { . . . (references to file using file_ptr) }
Note: The read and write subroutines also work on mapped files and produce the same data as when pointers are used to access the data.
- Close the file when the program is finished working with it:
close (fildes );
- Use the lseek subroutine to go to the end of file: