0

I was writing a small program which maps file and memory using mmap(). And searched a lot of places and found an interesting example from https://www.youtube.com/watch?v=m7E9piHcfr4

I wrote a short program based on the youtube video and works well. But what I want to do is a little different.

This example assumes a file which already has a content. What I want is

  1. use an existing file which is empty or create a file inside of the program.
  2. mmap() between a memory area and empty file
  3. update contents of the file by using pointer mmapped inside of the program.
  4. update contents of the file by accessing the file directly outside of the program.

Here is the code I mostly copied from the youtube video. And this code works well.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>

int32_t main(int32_t argc, char *argv[])
{
   struct stat sb;
   int32_t i;
   int32_t fd;
   int32_t ret;
   char *ptr;

   fd = open("./testfile", O_RDWR, S_IRUSR | S_IWUSR);
   if (fd < 0)
   {
      perror("file open error");
      return -1;
   }
   ret = fstat(fd, &sb);
   if (ret == -1)
   {
      perror("fstat error");
      return -1;
   }
   ptr = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

   printf("Printing file, as an array of characters...\n\n");
   for (i = 0 ; i < sb.st_size ; i++)
   {
      if ((i % 2) == 0)
      {
         ptr[i] = toupper(ptr[i]);
      }
      printf("%c", ptr[i]);
   }
   printf("\n");

   munmap(ptr, sb.st_size);
   close(fd);

   return 0;
}

Here is the code I made some change to do step1) ~ step4) above.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <sys/wait.h>

#define COLUMN 80
#define ROW 50
int32_t main(int32_t argc, char *argv[])
{
   struct stat sb;
   unsigned char *ptr;
   int32_t i;
   int32_t ret;
   int32_t fd;

   fd = open("my_test", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
   if (fd < 0)
   {
      perror("File Open Error");
   }

   ptr = mmap(
            NULL,
            COLUMN * ROW,
            PROT_READ | PROT_WRITE,
            MAP_SHARED,
            fd,
            0);
   for (i = 0 ; i < ROW ; i++)
   {
      sprintf(&ptr[i * COLUMN], "Line %d : \n", i);
   }

   ret = munmap(ptr, COLUMN * ROW);
   if (ret != 0)
   {
      printf("UnMapping Failed\n");
      return -1;
   }
   close(fd);

   return 0;
}

And I saw the message like below when I run this program.

$ ./mmm
Bus error (core dumped)

If you found what I did wrong, or have an idea how to do, please add your comment.

Cprogrammer
  • 153
  • 9

0 Answers0