[ Bottom of Page | Previous Page | Next Page | Contents | Index | Library Home | Legal | Search ]

General Programming Concepts:
Writing and Debugging Programs

Creating a Mapped Data File with the 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.

  1. To create the mapped data file:
    1. Open (or create) the file and save the file descriptor:

      if( ( fildes = open( filename , 2 ) ) < 0 )
      {
              printf( "cannot open file\n" );
              exit(1);
      }
    2. Map the file to a segment with the shmat subroutine:

      file_ptr=shmat (fildes, 0, SHM_MAP);

      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:

      #include <sys/shm.h>
  2. To detect the end of the mapped file:
    1. Use the lseek subroutine to go to the end of file:

      eof = file_ptr + lseek(fildes, 0, 2);

      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.

    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.
    3. Close the file when the program is finished working with it:

      close (fildes );

[ Top of Page | Previous Page | Next Page | Contents | Index | Library Home | Legal | Search ]