0

I'm trying to use shared memory between processes. I'm just implementing the features step-by-step. I keep getting Segmentation fault (core dumped) while I try to write something into it.

int* ms; // Pointer for milliseconds
int* ns; // Pointer for nanoseconds

void checkArgs(int argc, char* argv[]);
void createSharedMem();
void createSharedMem()
{
    int shmid = shmget(KEY, sizeof(int)*128, IPC_CREAT |0666 );
    if(shmid < 0)
        printf("\n Error creating shared memory");
    ms = shmat(shmid, NULL,0);
    ns = shmat(shmid,NULL,0);
    *ms = 0;
    *ns = 0;
}


int main(int argc, char* argv[])
{

    checkArgs(argc,argv);
    createSharedMem();            

    *ms = 1;
    *ns = 1;

    printf("ms : %d ns : %d", *ms,*ns);

}
mponagandla
  • 137
  • 13
  • Yeah, I thought it is going to ask for the code after I pressed continue, but it directly posted the question. Anyways, added now. ;) – mponagandla Feb 27 '19 at 03:06
  • As per the shared memory operation, this seems fine. and tried to execute this and it gets the shared memory fine and print is fine. is shmget() is getting success? is the segmentation fault is in checkArgs()? put more printf to check for the position of the crash. – Deepak Feb 27 '19 at 03:19
  • No, Error occurred since I added the variable to test if the data is being written to the shared mem. Until I added ms and ns, everything was fine. – mponagandla Feb 27 '19 at 03:21
  • I just found out that the shared memory isn't getting created. After removing all ms and ns assignments, I got "Error creating shared memory" from the check. – mponagandla Feb 27 '19 at 03:26

1 Answers1

0

I found the problem. Instead of defining a key using #define KEY and using that in the shmget(), I used key_t to create a key variable. This fixed the problem of "Invalid argument"

Here's the updated code:

void createSharedMem()
{
    key_t key;
    int shmid = shmget(key, 4096, 0666 | IPC_CREAT);
    if(shmid < 0)
        perror("\n Error creating shared memory");
    ms = shmat(shmid, NULL,0);
    ns = shmat(shmid,NULL,0);
    *ms =0
    *ns=0;
    printf("%d",*ms);
}
mponagandla
  • 137
  • 13
  • 1
    This key should have proper number, and should be unique for writing and reading process/thread to create the same shared memory id. this should be fine with hard coded value also. just pass 1000 as key and it should work fine. usually this key is generated using ftok (). – Deepak Feb 27 '19 at 04:00