x4k3p
x4k3p

Reputation: 1779

Unix/C: put a file into shared memory

Have a problem. I have a file which contents look like number:error_description. Now i need to put this file to shared memory (POSIX). If any contents are modified it should be saved to the base-file. There is a need to search in the content in the shared memory (results will be sent to a client over a message queue). How do I implement all this? First I thought I have to open (fopen("my_file", "r")) and then I have to create shared memory and mmap the file. Can someone help me?

edit:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
/*
 * \ /tmp/errors -> Error File
 */
#define MSGQ_HANDLER    "/error_handler"
#define PATH_TO_FILE    "/tmp/errors"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

int main(void) {

    int fd = open(PATH_TO_FILE, O_RDWR);
    struct stat file_stat;
    fstat(fd, &file_stat);
    printf("File size: %zd\n", file_stat.st_size);
    char *byte_ptr = mmap(NULL, file_stat.st_size, PROT_READ | PROT_WRITE,
                              MAP_SHARED, fd, 0);
    if(byte_ptr == MAP_FAILED){
        perror("error:");
    }


    while(1){
        printf("%s\n", byte_ptr);
        if(byte_ptr)
            exit(1);
    }

    return EXIT_SUCCESS;
}

So far it is what I have now. Read a line works. How do I change the content?

Upvotes: 2

Views: 4509

Answers (1)

Patrick Schl&#252;ter
Patrick Schl&#252;ter

Reputation: 11861

Don't use fopen and forget about shared memory (the sh* API I mean). mmap is all that's needed.

Open your file with open and the right options (read/write). Then use mmap with the option MAP_SHARED. All changes in the file will be reflected directly and visible to all processes that map the same file. On Linux and Solaris (on other systems I don't know, but it is not guaranteed by POSIX or any standard) you can even access the file concurrently with read/write. It is a bad idea though. Concurrent memory accesses from different processes will, of course, need synchronisation (mutex, semaphores etc.).

Upvotes: 3

Related Questions