0

I would like to share to use mmap. However it doesn't work, because I'm getting a segfault :

int fdL = open("/dev/zero", O_RDWR | O_CREAT);
int *ligneC = (int *) mmap(0, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED, fdL, 0);

*ligneC = 0;

Where am I wrong ?

g123k
  • 3,748
  • 6
  • 42
  • 45
  • You are specifying `O_CREAT` and missing the mode; still, that can't be the problem since I assume `/dev/zero` already exists. Is that all your code ? – cnicutar May 20 '11 at 18:59
  • The error is coming from : *ligneC = 0; I don't know why – g123k May 20 '11 at 19:04
  • Let me "rephrase" that: **is that all your code** ? – cnicutar May 20 '11 at 19:05
  • No, it is for a student project (matrix calculation with multiple processes), but for this step I have to use mmap. Is there another way to share the variable between all my processes ? – g123k May 20 '11 at 19:10
  • What I mean was that it shouldn't fail and something else is probably broken. – cnicutar May 20 '11 at 19:13

1 Answers1

1

Your code works fine for me. Try adding some error checks to your code. You will know what is failing and why:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>

int main(int argc,char*argv[])
{
    int fdL = open("/dev/zero", O_RDWR | O_CREAT);

    if(fdL<0)
    {
        perror("open");
        exit(1);
    }

    int *ligneC = (int *) mmap(0, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED, fdL, 0);

    if(ligneC==(int*)-1)
    {
        perror("mmap");
        exit(1);
    }

    *ligneC = 0;
    return 0;
}
Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65